Skip to main content

Unshift

Implement the generic version of Array.unshift

For example:

ts
type Result = Unshift<[1, 2], '3'> // [1, 2, '3']
Cannot find name 'Unshift'.2304Cannot find name 'Unshift'.
ts
type Result = Unshift<[1, 2], '3'> // [1, 2, '3']
Cannot find name 'Unshift'.2304Cannot find name 'Unshift'.
Solution ✅
ts
type Unshift<Arr, Value> = Arr extends readonly any[] ? [Value, ...Arr] : never
 
type Result = Unshift<[1, 2], 0> // [0, 1, 2,]
type Result2 = Unshift<[], 1> // [1]
type Result3 = Unshift<[1, 2], '3'> // ['3', 1, 2]
type Result4 = Unshift<['1', 2, '3'], boolean> // [boolean, '1', 2, '3']
ts
type Unshift<Arr, Value> = Arr extends readonly any[] ? [Value, ...Arr] : never
 
type Result = Unshift<[1, 2], 0> // [0, 1, 2,]
type Result2 = Unshift<[], 1> // [1]
type Result3 = Unshift<[1, 2], '3'> // ['3', 1, 2]
type Result4 = Unshift<['1', 2, '3'], boolean> // [boolean, '1', 2, '3']