#3192Medium

Reverse

Implement the type version of `Array.reverse()`. Learn tuple manipulation in TypeScript in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement the type version of Array.reverse().

Challenge Instructions: Reverse

Medium

Implement the type version of Array.reverse

For example:

type a = Reverse<['a', 'b']> // ['b', 'a']
type b = Reverse<['a', 'b', 'c']> // ['c', 'b', 'a']

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

ChallengeSolution
// Video Solution: https://youtube.com/watch?v=8a3_sxxtRnE

type cases = [
  Expect<Equal<Reverse<[]>, []>>,
  Expect<Equal<Reverse<['a', 'b']>, ['b', 'a']>>,
  Expect<Equal<Reverse<['a', 'b', 'c']>, ['c', 'b', 'a']>>,
]

type errors = [
  // @ts-expect-error
  Reverse<'string'>,
  // @ts-expect-error
  Reverse<{ key: 'value' }>,
]

Pro Challenge

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

One-time payment. Lifetime access.

Video Walkthrough

Detailed Explanation

type Reverse<T extends unknown[]> = T extends [...infer Rest, infer Last]
  ? [Last, ...Reverse<Rest>]
  : T

How it works:

This challenge helps you understand tuple manipulation and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge