Tuple To Union - medium - [Type Challenge]

강성훈·2023년 1월 26일
0

type-challenges

목록 보기
18/20
post-thumbnail

by Anthony Fu @antfu

문제

튜플 값으로 유니온 타입을 생성하는 제네릭 TupleToUnion<T>를 구현하세요.

type Arr = ['1', '2', '3']

type Test = TupleToUnion<Arr> // expected to be '1' | '2' | '3'

솔루션

typescript의 Indexed Access Types문법을 이용하여 union 타입으로 나타 낼 것이다.
Indexed Access Types

type TupleToUnion<T extends any[]> = T[number];

// type Test = "1" | "2" | "3"

배열의 인덱스가 number로 이루어져있기에 number를 입력한 것이다. any 타입이여도 작동하는데 지장 없을 것이다.

단 keyof T는 작동하지 않을 것이다.
array의 키에는 array의 값 뿐만 아니라 push, pop, sort와 같은 함수에 해당하는 타입도 존재하기에 원하는 값대로 나오지 않을 것이다.

type TupleToUnion<T extends any[]> = T[keyof T];

// type 결과
type Test = 3 | "1" | "2" | "3" | (() => string) | (() => string) | (() => "1" | "2" | "3") | ((...items: ("1" | "2" | "3")[]) => number) | {
    (...items: ConcatArray<"1" | "2" | "3">[]): ("1" | "2" | "3")[];
    (...items: ("1" | ... 2 more ... | ConcatArray<...>)[]): ("1" | ... 1 more ... | "3")[];
} | ... 25 more ... | (<A, D extends number = 1>(this: A, depth?: D) => FlatArray<...>[])
profile
고등학생 주니어 개발자

0개의 댓글