설계 의도
- 빈 배열인 경우는 never 타입 리턴하고, 그 외는 배열의 첫 번째 요소 리턴하도록 구현
코드
type First<T extends any[]> = T extends [] ? never : T[0]
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<First<[3, 2, 1]>, 3>>,
Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
Expect<Equal<First<[]>, never>>,
Expect<Equal<First<[undefined]>, undefined>>,
]
설계 의도
- 배열이나 튜플의 길이를 리턴하기 위해서 제네릭타입
T를 배열이나 튜플로 제한하기
코드
type Length<T extends readonly any[]> = T["length"]
import type { Equal, Expect } from '@type-challenges/utils'
const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const
const spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'] as const
설계의도
- 제네릭타입 T가 유니온 타입이므로, 각 유니온 멤버가 제네릭타입 U인지 조건부로 체크해서 해당하는 타입만 리턴하도록 처리
코드
type MyExclude<T, U> = T extends U ? never : T
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<MyExclude<'a' | 'b' | 'c', 'a'>, 'b' | 'c'>>,
Expect<Equal<MyExclude<'a' | 'b' | 'c', 'a' | 'b'>, 'c'>>,
Expect<Equal<MyExclude<string | number | (() => void), Function>, string | number>>,
]