beraliv

Exclude type under the hood in TypeScript

Example of Exclude use
Example of Exclude use

Sixth challenge is Exclude

Don't mix up Exclude with Omit:

Iteration over a union type

We already know how to iterate over:

For union types there are Distributive Conditional Types:

Example of Distributive Conditional type
Example of Distributive Conditional type

Let's check what's going on step by step:

Explanation of Distributive Conditional type example
Explanation of Distributive Conditional type example

So it's literally applied to each element of a union type 💫

We can use Distributive Conditional Types with different conditions:

  1. Type extends any
  2. Type extends unknown
  3. Reversed Type extends never (as this is false for every Type)
Explanation of never in Distributive Conditional type
Explanation of never in Distributive Conditional type

It works the same way because any and unknown are top types in TypeScript and never is bottom type.

Solution

For Exclude we want to do the same way but we need to remove specified elements from a union:

Explanation of the possible solution
Explanation of the possible solution

T extends U is what we need:

Solution
Solution

🔥🔥🔥 Great job!

Please check out the solution with test cases in Playground

typescript
Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter