Syntax
type Present = NonNullable<string | null | undefined>;Examples
Removing Nullish Members with NonNullable: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints 0,8; zero is preserved while null and undefined are removed.
function present<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined;
}
const values: (number | null | undefined)[] = [0, null, 4, undefined];
const numbers = values.filter(present);
console.log(numbers.map(value => value * 2).join(","));- Expected result: The program prints 0,8; zero is preserved while null and undefined are removed.
- The explicit nullish comparisons avoid accidentally discarding zero.
- The predicate connects runtime filtering to the NonNullable result type.
Best practices
- Enable strictNullChecks to get meaningful nullable-state checking.
- Avoid using a type assertion to pretend external data is non-null.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook