Advertisement
Advanced TypeScript, Conditional Types

How does TypeScript's built-in Exclude<T, U> utility type work internally, using conditional types?

Short answer

Exclude is implemented as a distributive conditional type: `type Exclude = T extends U ?

Save TypeScript mock interview
Advertisement
AModel answer
Exclude<T, U> is implemented as a distributive conditional type: `type Exclude<T, U> = T extends U ? never : T;` — because it distributes over a union T, each member that matches U is individually replaced with never (which effectively disappears from the resulting union), leaving only the members that don't match.
type Exclude<T, U> = T extends U ? never : T;
type A = Exclude<'a' | 'b' | 'c', 'a'>; // 'b' | 'c'
Real-world example
Understanding how many of TypeScript's built-in utility types (Exclude, Extract, NonNullable) are just thin wrappers over conditional types.
Likely follow-ups
  • How would you implement Extract<T, U>, the logical opposite of Exclude?
Related topics