泛型的第一个元素First<T>

实现一个First泛型,它接受一个数组T并返回它的第一个元素的类型。

例如:

type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]

type head1 = First // 应推导出 'a'
type head2 = First // 应推导出 3

解法:

type First = T extends [] ? never : T[0]

//or 

type First = T extends [infer first, ...any] ? first : never 

//or 

type First = T['length'] extends 0 ? T[0] : never

//or 

type First = T extends {lengh: 0} ? T[0] : never

你可能感兴趣的:(前端)