TypeScript Reference ยท Utility Types
TypeScript NonNullable<T> utility type
Reference for TypeScript NonNullable<T>: remove null and undefined from a type, how it works as an intersection, and how to use it in filters and guards.
NonNullable<T> removes null and undefined from T. Given string | null | undefined you get string. It is most useful when you have already checked a value (or filtered an array) and want to give the cleaned result an accurate type.
The compiler narrows variables automatically after an if (x != null) check, but it cannot always do the same for arrays or generic helpers. There, NonNullable<T> states what the code has just guaranteed.
type Maybe = string | null | undefined; type Definite = NonNullable<Maybe>; // string
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type NonNullable<T> = T & {};
| Name | Description |
|---|---|
T |
Any type. null and undefined are removed; everything else is kept. |
Result: T without null and undefined. NonNullable<null | undefined> is never.
Edge cases: intersecting with {} removes null and undefined but leaves unknown as {} (so NonNullable<unknown> is {}). Before TypeScript 4.8 the definition was the conditional T extends null | undefined ? never : T, which behaved the same for most unions.
Usage notes
- Type-level only. It does not check anything at runtime; use an
if,??or a guard function to remove missing values for real. - Under
strictNullChecks. The type is meaningful only withstrict(orstrictNullChecks) on. Without it,nullandundefinedare in every type already. - Narrowing on its own. After
if (x != null)the compiler narrowsxitself. Reach forNonNullablewhen the value is inside an array, a generic, or a property type you want to declare. - Filter with a type predicate.
Array.prototype.filterdoes not narrow by itself; a function returningvalue is NonNullable<T>does, as shown above. Newer compilers can also infer such predicates from simple arrow functions. - Does not touch properties.
NonNullable<{ a: string | null }>is unchanged; thenullis inside a property. Use a mapped type withNonNullableon each property for that. - Added in TypeScript 2.8; the intersection form in 4.8.
Related
Exclude<T, U>,Extract<T, U>,Required<T>- Lessons: Narrowing, Type Guards