TypeScript 7 reference · Utility Types
TypeScript NonNullable<Type> Utility Type
Remove null and undefined from a type, for values you've already checked or that can never be missing.
TypeScript 7 Since 2.8
Syntax
NonNullable<Type>
Parameters
| Parameter | Description |
|---|---|
Type |
The object type to transform. |
Return value
Type without null and undefined.
Examples
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>;
const n: Name = "Ana";
// @ts-expect-error: null is not allowed
const bad: Name = null;
console.log(n);
Output
Ana
function definitely<T>(value: T, message: string): NonNullable<T> {
if (value == null) throw new Error(message);
return value as NonNullable<T>;
}
const fromEnv: string | undefined = "8080";
const port = definitely(fromEnv, "PORT missing");
console.log(port.padStart(6, "."));
Output
..8080
Version history
| Version | Change |
|---|---|
| TypeScript 2.8 | Added |
Related
Required<Type>· Make every property of a type required, removing the ? from optional properties. The opposite of Partial.Exclude<UnionType, ExcludedMembers>· Remove members from a union type. Exclude<'a' | 'b' | 'c', 'a'> is 'b' | 'c'.- TypeScript Utility Types · tutorial