Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of NonNullable<T> in TypeScript [duplicate]

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;
like image 342
zsoumya Avatar asked May 29 '18 16:05

zsoumya


1 Answers

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

like image 79
Lachlan D Avatar answered Sep 21 '22 23:09

Lachlan D