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

Typescript类型体操 - First of Array

时间:2022-09-02 23:34:53浏览次数:83  
标签:Typescript extends expected Array type First

题目

中文

实现一个通用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,extends,expected,Array,type,First
From: https://www.cnblogs.com/laggage/p/16651667.html

相关文章