Definition of NonNullable<T> in TypeScript [duplicate]
Asked Answered
W

1

8

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;
Woodall answered 29/5, 2018 at 16:23 Comment(1)
conditional typesDario
B
2

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

Bloodworth answered 21/10, 2020 at 3:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.