#3057Easy

Push

Add elements to the end of tuples with TypeScript's type system. Master the spread operator and tuple manipulation in this easy-level challenge on TypeScriptPro.

Add elements to arrays at the type level with Push! ➕

In this easy-level challenge, you'll implement the generic version of Array.push in TypeScript's type system. This type takes a tuple and an element, returning a new tuple with the element appended to the end.

This challenge reinforces your understanding of the spread operator in tuple types and shows how TypeScript can model array operations at compile time. It's a fundamental building block for more complex array manipulations.

Challenge Instructions: Push

Easy

Implement the generic version of Array.push

For example:

[object Object]

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
/* _____________ Your Code Here _____________ */

type Push<T, U> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

type cases = [
  Expect<Equal<Push<[], 1>, [1]>>,
  Expect<Equal<Push<[1, 2], '3'>, [1, 2, '3']>>,
  Expect<Equal<Push<['1', 2, '3'], boolean>, ['1', 2, '3', boolean]>>,
]

type errors = [
  // @ts-expect-error
  Expect<Equal<Push<number[], string>, string[]>>,
  // @ts-expect-error
  Expect<Equal<Push<string[], number>, [string, number]>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Video Walkthrough

Detailed Explanation

The Push type uses the spread operator to append an element to a tuple.

[object Object]

How it works:

This elegantly models JavaScript's push operation at the type level, maintaining type safety for each element in the resulting tuple. The simplicity of this solution showcases TypeScript's expressive power.

This challenge is originally from here.

Share this challenge