I was looking for something like a Nullable type in TypeScript when I noticed that while there is no Nullable type (or is there?), there is a NonNullable
type defined in:
C:\Program Files\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.es6.d.ts
The definition of NonNullable
is:
/**
* Exclude null and undefined from T
*/
type NonNullable <T> = T extends null | undefined ? never : T;
Can someone please explain (or point me to the relevant documentation about) what this definition means? I could not locate the documentation around this. Specifically, I could not find what the ?
operator and the never
keyword means in the context of generic constraints.
I found other similar definitions in the same file:
/**
* Exclude from T those types that are assignable to U
*/
type Exclude<T, U> = T extends U ? never : T;
/**
* Extract from T those types that are assignable to U
*/
type Extract<T, U> = T extends U ? T : never;
Someone has pointed you in the direction of conditional types which is the second part of your question but for anyone else that stumbles upon this the opposite of NonNullable<T>
would be T | null | undefined
, basically just saying that it can be defined as T
or it can be null
or undefined
, you can read more about it here https://www.typescriptlang.org/docs/handbook/advanced-types.html#nullable-types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With