0
0
Typescriptprogramming~20 mins

Rest elements in tuples in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Tuple Rest Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of tuple with rest element in function parameter
What is the output of this TypeScript code when calling logTuple([1, 2, 3, 4])?
Typescript
function logTuple([first, ...rest]: [number, ...number[]]) {
  console.log(first, rest.length);
}
logTuple([1, 2, 3, 4]);
A1 3
B1 4
C1 0
DError: Tuple destructuring failed
Attempts:
2 left
💡 Hint
Remember that the rest element collects all remaining items after the first.
Predict Output
intermediate
2:00remaining
Length of tuple with rest element
What is the length of the tuple type T = [string, ...number[]] when assigned const x: T = ['hello', 1, 2, 3]?
Typescript
type T = [string, ...number[]];
const x: T = ['hello', 1, 2, 3];
console.log(x.length);
AError: Tuple length cannot be determined
B3
C1
D4
Attempts:
2 left
💡 Hint
The rest element allows any number of elements after the first.
🔧 Debug
advanced
2:00remaining
Identify the error with rest element in tuple type
Why does this TypeScript code cause an error?
Typescript
type T = [...number[], string];
const x: T = [1, 2, 3, 'end'];
ACannot mix number and string in tuple
BTuple cannot have more than 3 elements
CRest element must be last in tuple type
DNo error, code is valid
Attempts:
2 left
💡 Hint
Check the position of the rest element in the tuple type.
🚀 Application
advanced
2:00remaining
Function parameter with tuple rest element
Which function signature correctly accepts a tuple with a string followed by any number of booleans?
Afunction f([name, ...flags]: [string, ...boolean[]]) {}
Bfunction f([name, ...flags]: [...boolean[], string]) {}
Cfunction f([name, ...flags]: [string, boolean]) {}
Dfunction f([name, ...flags]: [boolean, ...string[]]) {}
Attempts:
2 left
💡 Hint
Rest element must be last and match the type of remaining elements.
🧠 Conceptual
expert
3:00remaining
Rest elements and tuple inference behavior
Given const t = [1, 2, 3] as const; and type T = [number, ...number[]];, what is the inferred type of t and does it satisfy T?
Typescript
const t = [1, 2, 3] as const;
type T = [number, ...number[]];
A<code>t</code> is readonly [1, 2, 3] but does not satisfy <code>T</code>
B<code>t</code> is readonly [1, 2, 3] and satisfies <code>T</code>
C<code>t</code> is mutable number[] and satisfies <code>T</code>
D<code>t</code> is mutable number[] but does not satisfy <code>T</code>
Attempts:
2 left
💡 Hint
Consider how as const affects tuple types and readonly status.