타입 스크립트 4버전으로 하길 추천한다.
/*
15 - Last of Array
-------
by Anthony Fu (@antfu) #medium #array #4.0
### Question
> TypeScript 4.0 is recommended in this challenge
Implement a generic `Last<T>` that takes an Array `T` and returns it's last element's type.
For example
```ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type tail1 = Last<arr1> // expected to be 'c'
type tail2 = Last<arr2> // expected to be 1
View on GitHub: https://tsch.js.org/15 */
/* _____________ Your Code Here _____________ */
type Last<T extends any[]> = any
/* _____________ Test Cases _____________ */ import { Equal, Expect } from '@type-challenges/utils'
type cases = [ Expect<Equal<Last<[3, 2, 1]>, 1>>, Expect<Equal<Last<[() => 123, { a: string }]>, { a: string }>>, ]
/* _____________ Further Steps _____________ / /
Share your solutions: https://tsch.js.org/15/answer View solutions: https://tsch.js.org/15/solutions More Challenges: https://tsch.js.org */
못 풀겠어서 답을 봤다.
기발한 솔루션이 많다.
```tsx
type Last<T extends any[]> = T extends [...infer _, infer L] ? L : never
많은 추천을 받은 방법
type Last<T extends any[]> = [any, ...T][T['length']]
type Last<T extends any[]> =
((...args: T) => any) extends (a: infer N, ...r: infer R) => any ? R['length'] extends 0 ? N : Last<R> : never