0
0
Typescriptprogramming~20 mins

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

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Tuple Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
A[42, undefined, true]
B[42, "", true]
C[42, true]
D[42, undefined]
Attempts:
2 left
💡 Hint
Remember that optional elements can be explicitly set to undefined.
Predict Output
intermediate
2: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);
A3
B1
C2
D0
Attempts:
2 left
💡 Hint
Optional elements may be missing in the actual array instance.
🔧 Debug
advanced
2: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];
ABoolean cannot be last element in tuple
BCannot assign undefined to optional elements
CMissing required elements in tuple
DToo many elements assigned; tuple only allows up to 3 elements
Attempts:
2 left
💡 Hint
Check how many elements the tuple type allows.
🧠 Conceptual
advanced
2: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;?
Aundefined
Bnull
Cempty string ""
Dthrows an error
Attempts:
2 left
💡 Hint
Optional elements may be missing and default to undefined when destructured.
Predict Output
expert
3: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]));
AName: Alice, Age: , Active: true
BName: Alice, Age: undefined, Active: true
CName: Alice, Age: unknown, Active: true
DName: Alice, Age: 0, Active: true
Attempts:
2 left
💡 Hint
The nullish coalescing operator (??) returns the right side if the left is null or undefined.