Skip to main content

Unshift

introduction#

Implement the type version of Array.unshift

For example

typescript
type Result = Unshift<[1, 2], 0>; // [0, 1, 2,]
typescript
type Result = Unshift<[1, 2], 0>; // [0, 1, 2,]
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type Unshift<T, U> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Unshift<[], 1>, [1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Unshift<[1, 2], 0>, [0, 1, 2]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Unshift<['1', 2, '3'], boolean>, [boolean, '1', 2, '3']>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
ts
/* _____________ Your Code Here _____________ */
type Unshift<T, U> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<Unshift<[], 1>, [1]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Unshift<[1, 2], 0>, [0, 1, 2]>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Unshift<['1', 2, '3'], boolean>, [boolean, '1', 2, '3']>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
take the challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type Unshift<T, U> = T extends [...infer Rest] ? [U, ...Rest] : never;
Try
ts
type Unshift<T, U> = T extends [...infer Rest] ? [U, ...Rest] : never;
Try
view more solutions