Repository navigation
Discussion on --strictOptionalProperties #44421
Description
Activity
- addedDiscussionIssues which may not have code impactIssues which may not have code impactMeta-IssueAn issue about the team, or the direction of TypeScriptAn issue about the team, or the direction of TypeScript
on Jun 3, 2021 - pinned this issue
on Jun 4, 2021 DanielRosenwasser commented
on Jun 4, 2021 MemberAuthorMore actionsNew Errors list from last night #44427 👀
Last night I tried updating pyright/pylance to a build of TS that included this to see how it would go. I'll try and sum up my thoughts...
I'm not sure that this check is going to end up being widely usable any time soon; I get loads of messages coming from the types of libraries I don't control, especially from the LSP client library (and spec), where they treat
?as equivalent toundefined. I think that this pattern is very common and unlikely go away.As for trying to fix our own code, the messaging is definitely bad; I found it very hard to try and locate the actual place I needed to make the change in a large project. I ended up starting tsc in watch mode, opening a file with an error in VS Code, then I see the problems (as VSC only shows errors in open files). Then, either the related diagnostic pointed back to the declaration (so I could jump and add
| undefined), or confusingly did not, in which case I had to go-to-def on the error'd expression to figure out what to change.I'm sure it could be improved to say something like "property had a
?but noundefined", but that is going to push everyone to add| undefined, in which case, is this check helping?Before I gave up, I still had hundreds of errors to fix. It seemed almost random which properties I needed to change, and I was left with a number of interfaces where some properties had
| undefinedand some did not, which tells me that at some point in the future, I may use a property in a new way and have to fix them.I'm not sure I've actually been able to find any bugs with this so far; maybe I'm too inclined to just try and stick
| undefinedeverywhere. I don't think we do anyinchecks, and only care about truthiness.I'm pretty surprised that this is on by default; it feels really noisy (far noisier than the not-default
noPropertyAccessFromIndexSignature) and I expect to have to disable it when I upgrade. I think it will be very surprising to users with"strict": trueto see this enabled.Reacted by Daniel Rosenwasser and MishIs the
Requiredutility type supposed to be removing an explicitundefined?I thought that it was supposed to just remove the
?.Reacted by Joe CalzarettaI believe language features should be a right balance between exactness and usability, i.e. a health dose of pragmatism.
With thisstrictOptionalProperties, I feel like we are sacrificing a lot of usability and readability, just for the purpose of exactness.
From my experience there are very little cases (in fact, I've never encountered any) where I care about whether a field isundefinedor missing (and if I ever did, there are ways to assert that).Now, because I use the
strictoption, I have to clutter all my types with| undefined.I guess the issue here stems from the fact that there are many levels of strictness, and because
strictis binary, thetruevalue meansall possible strictness rules. Maybe there could be several levels.Reacted by Daniel Rosenwasser, Sachin Raja, Katie Byers and Dana OredsonMaybe there could be several levels.
There are - set the individual flags you need. Multiple
strictlevels + individual options would just be way too much cognitive overhead IMO. If I'm at the point where I'm asking myself "Which level of strictness do I need?" I should probably be researching what exactly my options are anyway.Reacted by Pascal Heitz, Lauren Yim, Emanuel Lindström, Prabhdeep Singh Batth and MishFrom my experience there are very little cases (in fact, I've never encountered any) where I care about whether a field is undefined or missing (and if I ever did, there are ways to assert that).
Fun fact: When I used to write plain JS, I did
"foo" in objtests all the time. TS forced me out of that habit (very begrudgingly) because it had, until recently, no type-level way to distinguish between?and| undefined. So while I consider myself pragmatic, I'm hesitant to throw around pragmatism as an excuse here because I never considered the lack ofstrictOptionalPropertiesto be very pragmatic 😉Reacted by Daniel Rosenwasser, Mariusz Pawelski and vlinderFun fact: When I used to write plain JS, I did "foo" in obj tests all the time. TS forced me out of that habit (very begrudgingly) because it had, until recently, no type-level way to distinguish between ? and | undefined.
It does, you can create a type like
{foo: string} | {}if you wantfooto be optional but not allowundefinedas a value so the question is more about final type is more desirable and thus should be represented with the most ergonomic{foo?: string}syntax. Personally I beleave the old way is more common partly because of this statement in the initial post:We'd also have to update the lib.dom.d.ts generator to emit | undefined on most optional properties.
Which I also believe would be true for most third party libraries as well. If the new
strictOptionalPropertiesbehaviour was more common it would have been a widely requested feature up until now. However, now that I know about it I can just addstrictOptionalProperties: falseto all my tsconfigs so it's not a massive problem. Though if library authors start addingstrictOptionalProperties: falsethey would not catch this and release typings that causes problems forstrictOptionalProperties: trueso there is a small risk that this causes a lot of churn for both users and library authors.It does, you can create a type like
{foo: string} | {}if you wantfooto be optional but not allowundefinedas a valueconst oops: { foo: string } | {} = { foo: undefined }; // no error
Excess property checks only happen in specific situations, and they never happen for the empty object type
{}. There aren't any truly exact types (#12936) so even with excess property checking you could find fun ways to sneakundefined(or evenunknown) property values in there.it would have been a widely requested feature up until now
I guess "widely" is a subjective term, but #13195 does have a decent number of positive reactions, comments, and linked issues.
Reacted by Daniel Rosenwasser, Martin Johns and Ryan Cavanaugh{ foo: string } | { foo: never }then, it's always possible to type it if you actually need it. But I'm not arguing against the existence of this, as I said, I'll just disable it and move on.For the record, while that approach may work for small numbers of optional properties (3-4, tops), it would become combinatorially explosive very quickly.
Also, the
nevermay become an issue in the presence of other properties. By definition, I can't produce a value of type{ foo: string, bar: never }{ foo: string } | { foo: never }So
foois a required property, I guess? If this were a straightforward problem to solve by using existing language features, then it would have been done that way instead of by introducing a new compiler flag.Reacted by Martin JohnsRyanCavanaugh commented
on Jun 7, 2021 MemberMore actionsFor context, if we're looking at type system features, this was easily in the top 10 in terms of upvotes (it's behind only typed exception clauses, parametric types, nominal types, exact types, spread types, type guard inference, and
internal).I definitely hear the feedback, though -- some codebases consistently disavow any difference between
{ }and{ k: undefined }. If that's true in your codebase, turning this flag on is all pain and no gain.There are many APIs in JS that don't work like this, though (including the spread operator
...), and faithful typing of real JS API is our north star. I think it was truly a "missing" (ha) feature and the question is just how to get it out there in a way that isn't too painful, even if "too painful" means "too much to toggle a flag in your tsconfig".Reacted by Bruce Pascoe, Mariusz Pawelski, Dan Vanderkam, max-hk, Wojciech Pawlik and SancheZz11 remaining items
RyanCavanaugh commented
on Jun 22, 2021 MemberMore actionsJacek Karczmarczyk (@jacekkarczmarczyk) I'd write a standalone
copy(obj, list of keys)function (this is what I'd do even in untyped JS)Reacted by Jacek KarczmarczykLiteral object syntax is very useful and my concern as well with the new option.
The new syntax you propose, Jacek Karczmarczyk (@jacekkarczmarczyk), would be my preferred solution,
but it seems it is out-of-scope for typescript. Discussion: #39376
In javascript itself getting it in is a much harder task and I’m not sure it will ever happen.I tried the new option on our codebase and I think it is a step in the right direction:
- It actually has discovered one or two problems related to checking/overwriting undefined properties
- It finally makes type guards related to checking for optional properties be more precise (which is in line with the original goal).
- Though you can clearly see that the ecosystem of libraries still need to get on board to permanently enable the option.
The same problem described by Jacek Karczmarczyk (@jacekkarczmarczyk) also directly translates to JSX, and some ways to solve it:
const noop = () => {} const Buttons = ({ onFoo = noop, onBar, ...props, } : { onFoo?: () => void, onBar?: () => void, onBlub: () => void, onClick?: () => void, }) => { return <div> <button onClick={onFoo}>Do Foo</button> <button onClick={onBar ?? noop}>Do Bar</button> <button onClick={onBlub ?? noop}>Do Blub</button> <button {...props}>Click Me</button> </div> } const root = <Buttons onBlub={noop} />
Reacted by Raphael SchweikertHow about use
voidto exactly indicate a property is missing.interface Foo { prop: string | void; }
By the way, in
CorC++, if some function never receive parameters, it can declare argument asvoidvoid fn1() {} void fn2(void) {} fn1(1); // OK fn2(1); // Error
Reacted by Brian Kim- unpinned this issue
on Aug 11, 2021 I very much agree with this:
I believe language features should be a right balance between exactness and usability, i.e. a health dose of pragmatism.
With this strictOptionalProperties, I feel like we are sacrificing a lot of usability and readability, just for the purpose of exactness.
From my experience there are very little cases (in fact, I've never encountered any) where I care about whether a field is undefined or missing (and if I ever did, there are ways to assert that).Now, because I use the strict option, I have to clutter all my types with | undefined.
This feels like a real step backwards in terms of readability, and I, too, have rarely if ever come across a spot where I cared about the difference between a missing property and a property whose value is
undefined. Instead of making it so that code which doesn't care (which I contend is most code) has to specifically opt out of caring, it'd would've been great if code which does care had to opt in to caring.And sure, I can turn the flag off for my code, but I maintain one of those third party libraries discussed earlier, and so if I don't want to break my users who have this turned on, IIUC I more or less have to turn it on myself, or act like it's turned on, at least, right?
If so, I really don't like that this has been forced on us. Is there any way to add a flag to say, "Not only do I not care about the missing/undefined distinction in my own code, I want consumers of my code to be fine with it, too"? If my code doesn't act any differently based on the missing/undefined distinction, why should it matter which one an
exactOptionalPropertyTypes-using app passes me?Reacted by Brian KimReacted by Brian KimReacted by James MayIs there any way to add a flag to say, "Not only do I not care about the missing/undefined distinction in my own code, I want consumers of my code to be fine with it, too"? If my code doesn't act any differently based on the missing/undefined distinction, why should it matter which one an exactOptionalPropertyTypes-using app passes me?
Daniel Rosenwasser (@DanielRosenwasser) Ryan Cavanaugh (@RyanCavanaugh) - Pinging on this. Any chance you'd consider the above?
(Or perhaps I'm wrong about this?
if I don't want to break my users who have this turned on, IIUC I more or less have to turn it on myself, or act like it's turned on, at least, right?
)
RyanCavanaugh commented
on Dec 13, 2021 MemberMore actionsEvery strictness flag we've added since day 1 has implied work for upstream maintainers. We assessed the impact of this on DefinitelyTyped and other code bases and felt it was a worthwhile trade-off.
I'm not sure what sort of behavior you're describing with the suggestion. A concrete proposal of what specifically you think could work differently would be a good next step.
Reacted by Dana OredsonI'm not sure what sort of behavior you're describing with the suggestion. A concrete proposal of what specifically you think could work differently would be a good next step.
Sorry for not being clear. What I mean is this:
@sentry/browserdoesn't make the distinction between missing values and values set toundefined. If we were only building for ourselves, we'd setexactOptionalPropertyTypesto false and continue to just use optional properties in our types, and all would be well.But my understanding is that if anyone using
@sentry/browserhasexactOptionalPropertyTypesset to true, and they passundefinedin for some value we've marked as optional, they'll get an error. Currently, the only way for us to help such a user is to add| undefinedto all of our optional properties (or at least, any which might conceivably get passedundefined). Correct?What I'd like is not to have to do that, because IMHO it makes our types cluttered and harder to read, all in order to preserve a distinction our code doesn't make. So I wish there were a setting we could set along the lines of
pretendAllOptionalPropertiesInAnyTypesWeExportHaveAnOrUndefinedOnTheEnd. In other words, I'd like to be able to give users of@sentry/browserblanket permission to passundefinedin for any optional property in our types, even if those users haveexactOptionalPropertyTypesset to true.Hopefully that makes more sense. Failing such an option, perhaps there could be a new
??designation for properties, so thatsomeProp?: stringwould mean "pass a string or nothing at all" andsomeProp??: stringwould mean "pass a string or undefined or nothing at all" (with??essentially playing the role?used to play). Quite frankly I'd take anything which would make this work in a way which doesn't sacrifice so much readability in order to solve a problem which (as far as usage of our SDK is concerned) doesn't exist.Thanks.
Reacted by Ethan ResnickJust my 2 cents. I'm starting with typescript and stumbled upon this issue when trying to use this flag.
Here's my simple function:
async function health(signal?: AbortSignal): Promise<void> { const response = await fetch(`${backendUrl}/health`, { signal, }); const text = await response.text(); if (!response.ok) { throw new Error( "Failed to check health: " + `${response.status} ${response.statusText}: ${text}`, ); } }
I didn't find any ergonomic way to implement this code with new flag. Here's one way I've come with but it's ugly:
async function health(signal?: AbortSignal): Promise<void> { const response = await fetch(`${backendUrl}/health`, { ...(signal !== undefined ? { signal } : {}), }); const text = await response.text(); if (!response.ok) { throw new Error( "Failed to check health: " + `${response.status} ${response.statusText}: ${text}`, ); } }
I think there should be a language feature to support this compiler flag to allow for more ergonomic usage.
In this particular case with AbortSignal, there's actually another way:
signal: signal ?? nullbecause RequestInit declares signal assignal?: AbortSignal | null;. But I think that API like that is not always available.That said, I like this flag because it helped me to spot some weird API I designed (like using
x?: Xinstead ofx: X | undefined.RyanCavanaugh commented
on Feb 14, 2023 MemberMore actionsVladimir Bezhenar (@vbezhenar) I don't understand what's wrong with the upper snippet in your comment. It maybe sounds like what you're saying is that you want a way to construct an object literal that conditionally has a property slot?
Ryan Cavanaugh (@RyanCavanaugh) it does not compile with exactOptionalPropertyTypes.
Here's some declarations from lib.dom.d.ts:
declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>; interface RequestInit { ... signal?: AbortSignal | null; }So with exactOptionalPropertyTypes enabled I can't pass
undefinedtosignal.One work-around is to use second snippet: add property conditionally.
Another work-around is to pass
nullbecause this particular API allows to passnull, but not every API allows that.So, yes, a way to construct object that conditionally has a property slot with more ergonomic syntax would help.
I think someone already suggested syntax like:
fetch(url, { signal?: signal })Now I understand that TypeScript's philosophy is not to introduce syntax which deviates from JavaScript so I guess it's better to direct that kind of feedback to JavaScript standardization committee.
This has been mentioned above already, but in case you missed it, #39376 is the relevant typescript issue which was rejected and here is the tc39 discussion: https://es.discourse.group/t/optional-property-shorthand-in-object-literal/196
Reacted by Ryan CavanaughFor working with exactOptionalPropertyTypes code base I found this utility function to be super useful:
/** * Removes all undefined properties from an object. */ export function omitUndef<O extends object | undefined>(object: O): & { [K in keyof O as undefined extends O[K] ? never : K]: O[K] } & { [K in keyof O as undefined extends O[K] ? K : never]?: O[K] & ({} | null) } { if (object == undefined) return object as never; return Object.fromEntries( Object.entries(object).filter(([, v]) => v !== undefined), ) as never; }
We've pulled in a new feature called
--strictOptionalPropertieswhich sits under the--strictfamily of flags. If we were to start TypeScript over again, we believe the behavior ofstrictOptionalPropertieswould be on by default; however, this strictness option comes at a time when the community is much more mature with lots of existing code.I've opened up this issue to discuss some broader concerns so that we can ensure that
--strictOptionalPropertiesships smoothly and so we can hear some feedback from users.Off the bat, here's a few of my own concerns:
Discoverability of the Break
A user who upgrades TypeScript with
--stricton currently has no idea why their code has broken. At best, they will get an error likeWe can do better here, which is why I've opened up #44403.
Manual Upgrade Woes
The most permissive thing to do to fix breaks from
--strictOptionalPropertiesis to tack on an| undefinedonto every single?-marked optional property; however, this is incredibly tedious for an existing project.We'd like to provide some automated tooling to help alleviate this, which is why I've opened up #44419.
Surrounding Community Upgrade Woes
There are really 3 places that are outside most users' control that need to be upgraded to work correctly with
strictOptionalProperties:lib.d.ts@typespackages)The last one is the hardest to solve; however, the first two are way more automatable, and we can have the core team help with it, but it's definitely time taken away from other work, and that's a delicate tradeoff.
I haven't created an issue to manage this one, but I think it might be worth distributing segments of
lib.d.tsand some number of top packages to add| undefinedto the definitions and see if that helps. Ideally, automation from #44419 could help. We'd also have to update thelib.dom.d.tsgenerator to emit| undefinedon most optional properties.I'd like to get Ryan Cavanaugh (@RyanCavanaugh)'s thoughts on this one.
Other Feedback
I'm curious to hear feedback from users on this one - is it a useful option? Do you feel good about it and its purpose? Did it catch any interesting bugs? Let us know!