Exclude type under the hood in TypeScript
Created: 12 Apr 2021Updated: 12 Apr 2021
Sixth challenge is Exclude
Don't mix up Exclude with Omit:
Excludeis used for union typesOmitis used for object types so you can remove specified keys within it
Iteration over a union type
We already know how to iterate over:
- Object types (see Pick under the hood)
- Tuple types (see Making object out of tuple)
For union types there are Distributive Conditional Types:
Let's check what's going on step by step:
So it's literally applied to each element of a union type 💫
We can use Distributive Conditional Types with different conditions:
Type extends anyType extends unknown- Reversed
Type extends never(as this isfalsefor everyType)
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:
T extends U is what we need:
🔥🔥🔥 Great job!
Please check out the solution with test cases in Playground
typescript