출처: Type Challenges, https://github.com/type-challenges/type-challenges/blob/main/README.ko.md
43 - Exclude
`T`에서 `U`에 할당할 수 있는 타입을 제외하는 내장 제네릭 `Exclude<T, U>`를 이를 사용하지 않고 구현하세요.
type Result = MyExclude<'a' | 'b' | 'c', 'a'> // 'b' | 'c'
풀이
type MyExclude<T, U> = T extends U ? never : T;
타입스크립트의 타입시스템은 유니온 타입을 분배시켜 처리한다.
예를 들어 `'a' | 'b' | 'c' extends 'a'`라면 이는 `'a' extends 'a' | 'b' extends 'a' | 'c' extends 'a'`로 처리된다.
따라서 `MyExclude<'a' | 'b' | 'c', 'a'>`는 `'b' | 'c'`가 된다.
'알고리즘 > Type Challenges' 카테고리의 다른 글
268 - If (0) | 2023.09.06 |
---|---|
189 - Awaited (0) | 2023.09.06 |
18 - Length of Tuple (0) | 2023.09.06 |
14 - First of Array (0) | 2023.09.04 |
11 - Tuple to Object (0) | 2023.09.04 |