Hone logo
Hone
Problems

TypeScript Unshift Type

This challenge focuses on creating a custom TypeScript type that mimics the behavior of the unshift array method. You will learn how to manipulate array types and create generic utility types in TypeScript to achieve this functionality.

Problem Description

Your task is to create a generic TypeScript utility type called Unshift that takes two type arguments:

  1. T: An array type.
  2. U: The element type to be prepended to the array.

The Unshift type should return a new array type with U as the first element, followed by all the elements from T in their original order.

Key Requirements:

  • The Unshift type must be generic and accept an array type T and an element type U.
  • It should correctly prepend U to the beginning of the array type T.
  • The resulting type should be a tuple type if T is a tuple, and an array type if T is a general array type.

Expected Behavior:

If T is [1, 2, 3] and U is 0, Unshift<[1, 2, 3], 0> should result in [0, 1, 2, 3]. If T is string[] and U is number, Unshift<string[], number> should result in [number, ...string[]].

Edge Cases:

  • Handling empty tuple/array types: Unshift<[], 0> should result in [0].
  • Handling different types for T and U.

Examples

Example 1:

type OriginalTuple = [1, 2, 3];
type NewElement = 0;

type ResultTuple = Unshift<OriginalTuple, NewElement>;
// Expected: [0, 1, 2, 3]

Explanation: The NewElement 0 is prepended to the OriginalTuple [1, 2, 3].

Example 2:

type OriginalArray = string[];
type NewElementType = number;

type ResultArray = Unshift<OriginalArray, NewElementType>;
// Expected: [number, ...string[]]

Explanation: The NewElementType number is prepended to the general string[] array type.

Example 3:

type EmptyTuple = [];
type FirstElement = "start";

type ResultFromEmpty = Unshift<EmptyTuple, FirstElement>;
// Expected: ["start"]

Explanation: Prepending an element to an empty tuple results in a tuple with just that element.

Constraints

  • The solution must be implemented purely using TypeScript's type system.
  • No runtime code is expected. This is a type-level programming challenge.
  • The Unshift type should be as flexible as possible in handling various array and tuple types.

Notes

Consider how you can access and reconstruct tuple and array types in TypeScript. Think about the syntax for variadic tuple types and conditional types if needed. You might find the spread syntax (...) useful within type definitions.

Loading editor...
typescript