NonNullable
Concept and syntax
NonNullable<T> removes null and undefined from a type under strict null checking. It is not a runtime check and cannot turn a nullable value into a non-null value by itself. Narrow the value before assigning it to the derived contract.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Value=string|null|undefined; type Present=NonNullable<Value>; function show(x:Value){if(x==null)return "missing"; const p:Present=x; return p;}console.log(show("tea"),show(null));Expected output:
tea missingCommon mistake
Intentionally invalid; compile separately and do not execute.
type Value=string|null|undefined; type Present=NonNullable<Value>; function show(x:Value){if(x==null)return "missing"; const p:Present=x; return p;}const p:Present=null;Expected diagnostic: TS2322. Present excludes null; check the value or use a suitable fallback.
Practice and recap
Add number to Value and test zero without truthiness filtering.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
NonNullable — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about NonNullable is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Value=string|null|undefined; type Present=NonNullable<Value>; function show(x:Value){if(x==null)return "missing"; const p:Present=x; return p;}console.log(show("tea"),show(null));Which diagnostic and explanation match the rejected example under the lesson settings?
type Value=string|null|undefined; type Present=NonNullable<Value>; function show(x:Value){if(x==null)return "missing"; const p:Present=x; return p;}const p:Present=null;What does NonNullable<0 | false | null> evaluate to?