03. First Of Array
https://github.com/type-challenges/type-challenges/blob/master/questions/14-easy-first/README.md
https://ghaiklor.github.io/type-challenges-solutions/en/easy-first.html
문제
Implement a generic First<T>
that takes an Array T
and returns it’s first element’s type.
For example:
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
풀이
type First<T extends any[]> = ?;t
// 1. T에는 exnteds any[] 라는 제한이 걸려있다.
// 따라서 우리는 T 가 배열이라는 것을 가정할 수 있다.
// T가 배열일 때 예외가 생길 수 있는 경우는 비어있는 []인 경우다.
type First<T extends any[]> = T extends [] ? never : T[0]
문제는 너무 간단했다. conditional types
만 알면 바로 해결할 수 있다.
Last updated
Was this helpful?