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().
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).
// 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' }>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type Reverse<T extends unknown[]> = T extends [...infer Rest, infer Last]
? [Last, ...Reverse<Rest>]
: THow it works:
T to be an array.T extends [...infer Rest, infer Last]), while capturing the rest of the tuple (infer Rest) and the last element (infer Last).Last) and the rest of the tuple recursively passed into Reverse<Rest> ([Last, ...Reverse<Rest>]).T).This challenge helps you understand tuple manipulation and how to apply this concept in real-world scenarios.
This challenge is originally from here.