문제
배열(듀플) T를 받아 첫 원소의 타입을 반환하는 제네릭 First를 구현하세요.
예시
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3
🔥 도전하기
TS Playground - An online editor for exploring TypeScript and JavaScript
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
www.typescriptlang.org
풀이
해당 문제는 인덱스 접근 연산자를 사용해서 풀 수 있습니다.
하지만 여기서 주의해야 할 점은 빈 배열이 들어 왔을 경우, 해당 배열에는 아무 원소도 존재하지 않기 때문에 인덱스 접근 연산자(T[0])는 우리가 원하는 대로 정확하게 동작하지 않습니다.
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type arr3 = []
type First<T extends any[]> = T[0];
type head1 = First<arr1>
type head2 = First<arr2>
type head3 = First<arr3>
const newArr1:head1 = 'a';
const newArr2:head2 = 3;
const newArr3:head3 = undefined;
그렇기 때문에 배열의 첫번째 원소에 접근하기 전에, 해당 배열이 빈 배열인지 먼저 확인해야 합니다. 이때 조건부 타입을 사용하면 타입을 보다 명확하게 지정할 수 있습니다.
type First<T extends any[]> = T extends []? never : T[0];
'TypeScript > Type Challenges' 카테고리의 다른 글
[43] Exclude (0) | 2022.11.26 |
---|---|
[18] Length of Tuple (0) | 2022.11.19 |
[11] Tuple to Object (0) | 2022.11.09 |
[7] Readonly (0) | 2022.11.02 |
[4] Pick (0) | 2022.10.29 |