Add elements to the beginning of tuples with TypeScript. Learn tuple manipulation and spread operators in this easy-level challenge on TypeScriptPro.
Prepend elements to arrays at the type level with Unshift! ⬅️
In this easy-level challenge, you'll implement the type version of Array.unshift in TypeScript. This type takes a tuple and an element, returning a new tuple with the element added at the beginning.
Like its JavaScript counterpart, this type operation demonstrates how to manipulate tuple positions at compile time. You'll solidify your understanding of spread operators and tuple type construction.
Implement the type version of Array.unshift
For example:
[object Object]Change the following code to make the test cases pass (no type check errors).
/* _____________ Your Code Here _____________ */
type Unshift<T, U> = any
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'
type cases = [
Expect<Equal<Unshift<[], 1>, [1]>>,
Expect<Equal<Unshift<[1, 2], 0>, [0, 1, 2]>>,
Expect<Equal<Unshift<['1', 2, '3'], boolean>, [boolean, '1', 2, '3']>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
The Unshift type uses the spread operator to prepend an element to a tuple.
[object Object]How it works:
T extends unknown[] ensures T is an array type[U, ...T] places U first, then spreads all elements of TThis mirrors JavaScript's unshift method perfectly, showing how TypeScript's type system can model array operations with the same intuitive syntax used at runtime.
This challenge is originally from here.