其他分享
首页 > 其他分享> > Typescript类型体操 - First of Array

Typescript类型体操 - First of Array

作者:互联网

题目

中文

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

例如:

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

英文

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 extends { length: infer U } ? U extends 0 ? never : T[0] : never;

在线演示

标签:Typescript,head2,never,extends,expected,Array,type,First
来源: https://www.cnblogs.com/laggage/p/16651667.html