Exclude under the hood

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

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

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

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

T extends U is what we need:

Solution

🔥🔥🔥 Great job!

Please check out the solution with test cases in Playground

typescripteasy

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️