Implement the type version of ```Array.shift``` Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement the type-level version of Array.shift, which removes the first element from a tuple type and returns the remaining elements.
Implement the type version of Array.shift
For example
type Result = Shift<[3, 2, 1]> // [2, 1]Change the following code to make the test cases pass (no type check errors).
type Shift<T extends unknown[]> = T extends [infer _First, ...infer Rest]
? Rest
: []How it works:
T extends unknown[] ensures that Shift only accepts array/tuple types, causing a type error for non-array inputs like unknown (as required by the @ts-expect-error test case).infer to pattern-match the tuple: [infer _First, ...infer Rest] destructures the tuple into the first element and all remaining elements.Rest -- the tuple with the first element removed.[]), we return [].An alternative approach using variadic tuple types:
type Shift<T extends unknown[]> = T extends [unknown, ...infer Rest]
? Rest
: []This version skips naming the first element entirely since we do not need it, using unknown as a placeholder instead.
This challenge helps you understand tuple type destructuring with conditional inference and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount