🔷 TypeScript Intermediate

What is the NonNullable utility type?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

NonNullable<T> removes null and undefined from a type. Implementation: type NonNullable<T> = T & {} or equivalently type NonNullable<T> = T extends null | undefined ? never : T. Example: type MaybeString = string | null | undefined; type DefiniteString = NonNullable<MaybeString>; — result is string. Useful when you have received a value that TypeScript considers nullable but you have verified it is not null (perhaps via an assertion or runtime check). Often used with function return types: type UserOrNothing = User | null | undefined; type GuaranteedUser = NonNullable<UserOrNothing>;. In strict mode with strictNullChecks, you frequently need to remove nullability after runtime checks. Compare with the non-null assertion (!): NonNullable is a type-level transformation; the ! operator is an expression-level assertion that tells the compiler "this specific value is not null."

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a TypeScript codebase.