Exclude and Extract
Concept and syntax
Exclude<T,U> removes union members assignable to U; Extract<T,U> retains those members. They filter by assignability, not arbitrary substring matching or structural key deletion. A broad primitive is not split into every possible literal.
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 Mode="read"|"write"|"admin"; type Public=Exclude<Mode,"admin">; type Write=Extract<Mode,"write"|"delete">;const p:Public="read"; const w:Write="write"; console.log(p,w);Expected output:
read writeCommon mistake
Intentionally invalid; compile separately and do not execute.
type Mode="read"|"write"|"admin"; type Public=Exclude<Mode,"admin">; type Write=Extract<Mode,"write"|"delete">;const p:Public="admin";Expected diagnostic: TS2322. admin is excluded from the public union.
Practice and recap
Evaluate Exclude<string,"admin"> and explain why it is string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exclude and Extract — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Exclude and Extract is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Mode="read"|"write"|"admin"; type Public=Exclude<Mode,"admin">; type Write=Extract<Mode,"write"|"delete">;const p:Public="read"; const w:Write="write"; console.log(p,w);Which diagnostic and explanation match the rejected example under the lesson settings?
type Mode="read"|"write"|"admin"; type Public=Exclude<Mode,"admin">; type Write=Extract<Mode,"write"|"delete">;const p:Public="admin";What is Exclude<string,"admin">?