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 _____________ */typeFirst <T extends any[]> = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]typeerrors = [// @ts-expect-errorFirst <'notArray'>,// @ts-expect-errorFirst <{ 0: 'arrayLike' }>,]
ts
/* _____________ Your Code Here _____________ */typeFirst <T extends any[]> = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]typeerrors = [// @ts-expect-errorFirst <'notArray'>,// @ts-expect-errorFirst <{ 0: 'arrayLike' }>,]
my solution
Spoiler warning // Click to reveal answer
ts
typeFirst <T extends any[]> =T extends [] ? never :T [0];
ts
typeFirst <T extends any[]> =T extends [] ? never :T [0];
ts
//实现2typeFirst <T extends any[]> =T ['length'] extends 0 ? never :T [0]
ts
//实现2typeFirst <T extends any[]> =T ['length'] extends 0 ? never :T [0]
ts
// 实现3typeFirst <T extends any[]> =T [number] extends never ? never :T [0]
ts
// 实现3typeFirst <T extends any[]> =T [number] extends never ? never :T [0]
ts
// 实现4typeFirst <T extends any[]> =T extends [inferF , ...inferRest ] ?F : never
ts
// 实现4typeFirst <T extends any[]> =T extends [inferF , ...inferRest ] ?F : never