Typescript类型体操 - Last of Array
题目
中文
实现一个通用Last<T>
,它接受一个数组T
并返回其最后一个元素的类型。
例如
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
English
Implement a generic Last<T>
that takes an Array T
and returns its last element.
For example
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
答案
type Last<T extends any[]> = T extends [infer L, ...infer R] ? (R['length'] extends 0 ? L : Last<R>) : never;