/*
14 - First of Array
-------
by Anthony Fu (@antfu) #easy #array #4.0
### Question
Implement a generic `First<T>` that takes an Array `T` and returns it's first element's type.
For example
```ts
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
View on GitHub: https://tsch.js.org/14 */
/* _____________ Your Code Here _____________ */
type First<T extends any[]> = any
/* _____________ Test Cases _____________ */ import { 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>> ]
/* _____________ Further Steps _____________ / /
Share your solutions: https://tsch.js.org/14/answer View solutions: https://tsch.js.org/14/solutions More Challenges: https://tsch.js.org */
0 번째 인덱스로 접근하면 1, 2 번 테스트는 가볍게 통과한다. 그러나 3번째 테스트에서 never가 아닌 undefined가 나온다. 그래서 조건 문으로 never를 리턴해 주었다.
```tsx
type First<T extends any[]> = T[0] extends undefined ? never : T[0]
문제 업그레이드 됨
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>>
]
마지막 케이스 추가됨
답
type First<T extends any[]> = T['length'] extends 0 ? never : T[0]