Yuzhe's Blog

yuzhes

3060 · Unshift

Posted at # TypeScript # TypeChallenge # TC-Easy
EN ·

3060 · Unshift

Challenge Link

Problem

Implement the type version of Array.unshift.

type Result = Unshift<[1, 2], 0> // [0, 1, 2]

Solution

type Unshift<T extends any[], U> = [U, ...T]

Explanation

We use tuple spreading to construct a new tuple that prepends U before all elements of T.

Step by step:

  1. T extends any[] — constrains T to be an array/tuple type
  2. [U, ...T] — places U first, then spreads all elements of T

This is the mirror of Push: instead of appending to the end, we prepend to the beginning — matching what Array.prototype.unshift does at runtime.

Key concept: