Challenge - 5 Problems
Tuple Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of tuple with optional element
What is the output of this TypeScript code when compiled and run with
console.log(result)?Typescript
type MyTuple = [number, string?, boolean]; const result: MyTuple = [42, undefined, true]; console.log(result);
Attempts:
2 left
💡 Hint
Remember that optional elements can be explicitly set to undefined.
✗ Incorrect
The tuple type allows the second element to be optional. Here it is explicitly set to undefined, so the output includes it as undefined.
❓ Predict Output
intermediate2:00remaining
Length of tuple with optional elements
What is the value of
arr.length after this code runs?Typescript
type TupleOpt = [string, number?, boolean?]; const arr: TupleOpt = ["hello"]; console.log(arr.length);
Attempts:
2 left
💡 Hint
Optional elements may be missing in the actual array instance.
✗ Incorrect
The array has only one element assigned, so its length is 1 even though the tuple type allows more elements.
🔧 Debug
advanced2:00remaining
Why does this tuple assignment cause an error?
This code causes a TypeScript error. What is the reason?
Typescript
type T = [number, string?, boolean?]; const val: T = [10, undefined, undefined, true];
Attempts:
2 left
💡 Hint
Check how many elements the tuple type allows.
✗ Incorrect
The tuple type allows a maximum of 3 elements. The code tries to assign 4 elements, causing an error.
🧠 Conceptual
advanced2:00remaining
Behavior of optional elements in tuple destructuring
Given the tuple
type T = [number, string?, boolean?] and const t: T = [5], what is the value of second after const [, second] = t;?Attempts:
2 left
💡 Hint
Optional elements may be missing and default to undefined when destructured.
✗ Incorrect
Since the second element is optional and missing, destructuring assigns undefined to second.
❓ Predict Output
expert3:00remaining
Output of function using tuple with optional elements
What is the output of this TypeScript code?
Typescript
type MyTuple = [string, number?, boolean?]; function describe(t: MyTuple): string { const [name, age, active] = t; return `Name: ${name}, Age: ${age ?? "unknown"}, Active: ${active ?? false}`; } console.log(describe(["Alice", undefined, true]));
Attempts:
2 left
💡 Hint
The nullish coalescing operator (??) returns the right side if the left is null or undefined.
✗ Incorrect
The age is undefined, so the expression age ?? "unknown" evaluates to "unknown". The active is true, so it stays true.