跳到主要内容

First of Array

介绍

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

For example

ts
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
ts
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

start point

ts
/* _____________ Your Code Here _____________ */
type First<T extends any[]> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<First<[3, 2, 1]>, 3>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[]>, never>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[undefined]>, undefined>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
type errors = [
// @ts-expect-error
First<'notArray'>,
// @ts-expect-error
First<{ 0: 'arrayLike' }>,
]
ts
/* _____________ Your Code Here _____________ */
type First<T extends any[]> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<First<[3, 2, 1]>, 3>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[]>, never>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[undefined]>, undefined>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
type errors = [
// @ts-expect-error
First<'notArray'>,
// @ts-expect-error
First<{ 0: 'arrayLike' }>,
]

my solution

Spoiler warning // Click to reveal answer
ts
type First<T extends any[]> = T extends [] ? never : T[0];
ts
type First<T extends any[]> = T extends [] ? never : T[0];
ts
//实现2
type First<T extends any[]> = T['length'] extends 0 ? never : T[0]
ts
//实现2
type First<T extends any[]> = T['length'] extends 0 ? never : T[0]
ts
// 实现3
type First<T extends any[]> = T[number] extends never ? never : T[0]
ts
// 实现3
type First<T extends any[]> = T[number] extends never ? never : T[0]
ts
// 实现4
type First<T extends any[]> = T extends [infer F, ...infer Rest] ? F : never
 
ts
// 实现4
type First<T extends any[]> = T extends [infer F, ...infer Rest] ? F : never
 
Checkout more Solutions