Disclosure

Most of the problems under my TypeHero Challenges folder were either obtained from typehero.dev or from type-challenges repo. Purpose of these articles are just to document my approaches for my easy reference. Please visit the respective links for more info.

Link to original

Problem Description

Implement the built-in Exclude<T, U>

Exclude from T those types that are assignable to U

For example:

type Result = MyExclude<'a' | 'b' | 'c', 'a'> // 'b' | 'c'

Solutions

Approach 1

type MyExclude<T, U> = T extends U ? never : T

Suppose T = 'a' | 'b' | 'c' and U = 'a'. This works as if we’re looping through each item in T and comparing it to U:

  1. Does 'a' extend 'a'? Skip.
  2. Does 'b' extend 'a'? No, so keep.
  3. Does 'c' extend 'a'? No, so keep.
  4. Form a union of the kept values, i.e, 'b' | 'c'.