Last
介绍
实现一个Last<T>
泛型,它接受一个数组T
并返回其最后一个元素的类型。
例如
ts
type arr1 = ['a', 'b', 'c']type arr2 = [3, 2, 1]type tail1 = Last<arr1> // 应推导出 'c'type tail2 = Last<arr2> // 应推导出 1
View on GitHubts
type arr1 = ['a', 'b', 'c']type arr2 = [3, 2, 1]type tail1 = Last<arr1> // 应推导出 'c'type tail2 = Last<arr2> // 应推导出 1
start point
ts
/* _____________ Your Code Here _____________ */typeLast <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[]>, never>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[2]>, 2>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[3, 2, 1]>, 1>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[() => 123, {a : string }]>, {a : string }>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeLast <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[]>, never>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[2]>, 2>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[3, 2, 1]>, 1>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Last <[() => 123, {a : string }]>, {a : string }>>,]
my solutions
Spoiler warning // Click to reveal answer
ts
//方案1typeLast <T extends any[]> =T ['length'] extends 0 ? never :T extends [...inferR , inferL ] ?L : never
ts
//方案1typeLast <T extends any[]> =T ['length'] extends 0 ? never :T extends [...inferR , inferL ] ?L : never
ts
// 方案2typeLast <T extends any[]> =T extends [...inferR , inferL ] ?L : never
ts
// 方案2typeLast <T extends any[]> =T extends [...inferR , inferL ] ?L : never
ts
// 方案3 most populartypeLast <T extends any[]> = [never, ...T ][T ['length']]
ts
// 方案3 most populartypeLast <T extends any[]> = [never, ...T ][T ['length']]