-
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
Using conditional typing to check for extends null
does not seem to work correctly
#29627
Comments
You have flipped the branches in type DoesntCheckNull<T> = {
readonly [P in keyof T]: null extends T[P] ? false : true;
}; |
@jack-williams, that works! I have no idea why. I don't understand why type NonNullable<T> = T extends null | undefined ? never : T; |
For any types The type Always having a Hope that makes sense! |
Yes, that makes sense, thank you! Seems like this issue can be closed as working as designed. I'm still confused why the lib.es5.d.ts file has the |
@smithmb-code
When you put the type parameter on the left hand side you get a distributive conditional type. This lets you do filtering on the type, so you can return the non-nullable parts. When you put the type parameter on the right hand side you reduce the conditional type to basically a yes/no answer. type NonNullable<T> = T extends null ? never : T;
type IsNullable<T> = null extends T ? T : never
NonNullable<number | string | null> // returns number | string, filtering null.
Nullable<number | string | null> // just returns the original type number | string | null |
Wow, that all makes sense now. Thanks again for explaining it! I see it explained in the docs now too. |
Don't feel too bad @smithmb-code, sometimes I make the mistake myself of thinking I can use |
TypeScript Version: 3.3.0-dev.201xxxxx
Search Terms:
Domain: Conditional Types
extends null
Code
Expected behavior:
The
DoesntCheckNull<T>
should have the same result asDataWhichArentNull<T>
because it re-uses the logic inNonNullable<T>
i.e.
DataWhichAreAllTrue
should look like:Actual behavior:
DataWhichAreAllTrue
actually looks like:Playground Link:
playground N.B. turn on
--strictNullChecks
flag in OptionsRelated Issues:
Possibly related to 25413.
I thought it was related to 23843, but that was fixed in a PR that was merged 19 days ago, but I could reproduce this issue even when using typescript@next.
The text was updated successfully, but these errors were encountered: