Utility Types - NonNullable
In this page:
Basic NonNullable
NonNullable<T> removes null and undefined from a type T while preserving every other member of the union, narrowing a type that could be nullable into one that's guaranteed not to be.
Example: Basic NonNullable
type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
const s: DefiniteString = "hello";
console.log(s);
NonNullable with Functions
NonNullable can clean up the return type of functions that may otherwise return null or undefined, which is useful once the caller has already handled or ruled out the nullable case.
Example: NonNullable with Functions
function findUser(id: number): string | undefined {
return id === 1 ? "Ravi" : undefined;
}
type FoundUser = NonNullable<ReturnType<typeof findUser>>;
const name: FoundUser = "Ravi";
console.log(name);
NonNullable with Objects
NonNullable is useful when object properties or values can be null or undefined at the API boundary, but internal code wants a stricter, always-present type after validation has already ruled those cases out.
Example: NonNullable with Objects
interface ApiResponse {
data: string | null;
}
type ValidatedData = NonNullable<ApiResponse["data"]>;
const data: ValidatedData = "payload";
console.log(data);
NonNullable with Unions
NonNullable can remove null and undefined from larger unions with several other members, retaining every other valid type in the union while stripping only the nullable parts, leaving the rest of the union exactly as it was.
Example: NonNullable with Unions
type Value = string | number | null | undefined;
type CleanValue = NonNullable<Value>;
const v: CleanValue = 42;
console.log(v);
When to Use NonNullable
Use NonNullable when a type represents a value that has already been checked for null or undefined elsewhere, so the rest of the code doesn't need to keep re-checking for it.
Example: When to Use NonNullable
function getLength(value: string | null): number {
const checked: NonNullable<typeof value> = value ?? "";
return checked.length;
}
console.log(getLength("hello"));
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates