-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proposal: Add type Optional<T>
#20984
Comments
This is related to #13195, I think. My offhand suggestion there was to use EDIT: I feel that #13195 is the underlying issue: TypeScript doesn't really let you consistently distinguish a missing property key from an undefined property value. They are similar enough in practice that it usually doesn't matter, but different enough to be annoying (e.g., TypeScript will yell at you if you leave out a property whose value can be |
@jcalz that does seems related but the issue I want to address is that there is no way to map a particular property to be optional when using mapped types--it's all or nothing with the Your suggestion would solve this issue though. If |
Would something like |
That works if you know what |
I think conditional types fixes this |
Context/use case
I think it would be really useful to have a library that allows javascript users to define interfaces without using typescript syntax. This is my attempt at it (inspired by React's PropTypes):
This is a really motivating use case for me because I could create factory functions that create React stateless components or classes that add PropTypes and also capture the type the PropTypes define. Javascript users could use typescript without using typescript (but this proposal goes beyond my motivation).
The issue
But here's the issue:
There no way (that I know of) to map a particular property to be optional. I understand the type
Partial<T>
exists but this asserts that all of the properties are optional instead of just one.Even if the type of
optionalNumberParam
isnumber | undefined
, the typescript compiler still requires me to putoptionalNumberParam: undefined
in the object literal of the prop for the error to go away.I opened a stackoverflow question about this topic here.
Proposal
A possible solution to this problem would be to introduce a special type
type Optional<T>
.The type would be equal to this:
and additionally, the
Optional<T>
type would assert that on whichever parent the type is used on, it will be optional.So the interface
PropType
would go from:to:
Code examples
Simple example
These interfaces would be synonymous (though, I prefer the first syntax):
Primary/complex example again
The text was updated successfully, but these errors were encountered: