How would you write a generic 'assertIsDefined' utility using 'never' and TypeScript's assertion function syntax to narrow away null/undefined?
Short answer
Declare a function with an 'asserts value is T' return type (a TypeScript assertion function) that throws (returning 'never' internally) if the value is null or undefined — after calling it, TypeScript automatically narrows the checked variable's type at every subsequent line in…
Advertisement
AModel answer
Declare a function with an 'asserts value is T' return type (a TypeScript assertion function) that throws (returning 'never' internally) if the value is null or undefined — after calling it, TypeScript automatically narrows the checked variable's type at every subsequent line in that scope, without needing an explicit if-check wrapping the rest of the code.
function assertIsDefined<T>(value: T, message = 'Value is not defined'): asserts value is NonNullable<T> {
if (value === null || value === undefined) {
throw new Error(message);
}
}
function process(user: User | undefined) {
assertIsDefined(user);
console.log(user.name); // narrowed to User, no more '| undefined', for the rest of this scope
}Real-world example
Removing repetitive null-checking boilerplate in functions that need to guarantee a value is defined before proceeding, common in test helpers and validation layers.
Likely follow-ups
- How does an 'asserts' function's narrowing effect differ from a regular 'value is T' type predicate function's effect?
Related topics