跳到主要内容

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
ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type tail1 = Last<arr1> // 应推导出 'c'
type tail2 = Last<arr2> // 应推导出 1
View on GitHub

start point

ts
/* _____________ Your Code Here _____________ */
 
type Last<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
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 }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
 
 
ts
/* _____________ Your Code Here _____________ */
 
type Last<T> = any
 
/* _____________ Test Cases _____________ */
type cases = [
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 }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
 
 
take the challenge

my solutions

Spoiler warning // Click to reveal answer
ts
//方案1
type Last<T extends any[]> = T['length'] extends 0 ? never : T extends [...infer R, infer L] ? L : never
 
ts
//方案1
type Last<T extends any[]> = T['length'] extends 0 ? never : T extends [...infer R, infer L] ? L : never
 
ts
// 方案2
type Last<T extends any[]> = T extends [...infer R, infer L] ? L : never
 
ts
// 方案2
type Last<T extends any[]> = T extends [...infer R, infer L] ? L : never
 
ts
// 方案3 most popular
 
type Last<T extends any[]> = [never, ...T][T['length']]
 
ts
// 方案3 most popular
 
type Last<T extends any[]> = [never, ...T][T['length']]
 
view more solutions