跳到主要内容

Shift

介绍

Implement the type version of Array.shift

ts
type Result = Shift<[3, 2, 1]> // [2, 1]
ts
type Result = Shift<[3, 2, 1]> // [2, 1]
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type Shift<T> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
// @ts-expect-error
Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.
Shift<unknown>,
Expect<Equal<Shift<[]>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Shift<[1]>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Shift<[3, 2, 1]>, [2, 1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Shift<['a', 'b', 'c', 'd']>, ['b', 'c', 'd']>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type Shift<T> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
// @ts-expect-error
Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.
Shift<unknown>,
Expect<Equal<Shift<[]>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Shift<[1]>, []>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Shift<[3, 2, 1]>, [2, 1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Shift<['a', 'b', 'c', 'd']>, ['b', 'c', 'd']>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type Shift<T extends any[]> = T extends [infer F, ...infer R] ? R : [];
 
 
 
ts
type Shift<T extends any[]> = T extends [infer F, ...infer R] ? R : [];
 
 
 
view more solutions