Exclude, Extract, and NonNullable
Exclude, Extract, and NonNullable — the core idea
Exclude<T,U> removes assignable union members, Extract<T,U> keeps matching ones, and NonNullable<T> removes null and undefined. They help express constrained APIs without duplicating unions.
What you’ll learn
- Explain exclude, extract, and nonnullable with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: Exclude leaves loading | done. Extract selects done. NonNullable retains idle | loading | done. The strings assigned to these types are what the runtime displays.
Keep the boundary clear: NonNullable<T> does not throw when a runtime value is null; it simply changes the accepted compile-time type.
See the idea as a flow
Run the complete TypeScript example
Save the code as exclude-extract-nonnullable.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type State = "idle" | "loading" | "done" | null;
type Active = Exclude<State, "idle" | null>;
type Finished = Extract<State, "done">;
type Present = NonNullable<State>;
const a: Active = "loading";
const b: Finished = "done";
const c: Present = "idle";
console.log([a, b, c].join(" / "));Verified output
loading / done / idleBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable exclude-extract-nonnullable.ts; run: node exclude-extract-nonnullable.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
Exclude leaves loading | done. Extract selects done. NonNullable retains idle | loading | done. The strings assigned to these types are what the runtime displays.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
NonNullable<T> does not throw when a runtime value is null; it simply changes the accepted compile-time type.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Add "failed" to State and decide which of the three types includes it.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
Exclude<T,U> removes assignable union members, Extract<T,U> keeps matching ones, and NonNullable<T> removes null and undefined.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.