0
0
Typescriptprogramming~5 mins

Optional elements in tuples in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to have optional elements in a tuple in TypeScript?
It means some elements in the tuple can be left out when creating the tuple. These elements are marked with a question mark (?) after their type.
Click to reveal answer
beginner
How do you declare an optional element in a TypeScript tuple?
You add a question mark (?) after the type of the element inside the tuple. For example: [string, number?] means the second element is optional.
Click to reveal answer
beginner
What happens if you omit an optional element in a tuple when assigning a value?
The tuple still works fine. The optional element is simply missing, and TypeScript understands it as undefined or not present.
Click to reveal answer
intermediate
Can optional elements only be at the end of a tuple in TypeScript?
Yes, optional elements must come after all required elements. You cannot have a required element after an optional one in a tuple.
Click to reveal answer
beginner
Example: What is the type of [string, number?] and which values are valid?
This tuple requires a string first, and optionally a number second. Valid values include ["hello"] and ["hello", 42]. But [42] is invalid because the first element must be a string.
Click to reveal answer
How do you mark an element as optional in a TypeScript tuple?
AUse the keyword 'optional' before the element
BAdd a question mark (?) before the element's type
CUse square brackets around the element
DAdd a question mark (?) after the element's type
Which of these tuples is valid if the second element is optional? <br> A) [number?, string] <br> B) [string, number?] <br> C) [string?, number] <br> D) [number, string?]
A[number?, string]
B[string?, number]
C[string, number?]
D[number, string?]
If you have a tuple type [string, number?], which of these is a valid value?
A[]
B["hello"]
C["hello", "world"]
D[42]
What happens if you omit an optional element in a tuple?
AThe tuple works and the optional element is undefined
BThe tuple is invalid
CTypeScript throws an error
DThe tuple automatically fills the element with zero
Can you have a required element after an optional element in a tuple?
ANo, optional elements must be last
BYes, always
COnly if you use 'any' type
DOnly in arrays, not tuples
Explain how to declare and use optional elements in TypeScript tuples.
Think about how you can leave some parts out when making a tuple.
You got /4 concepts.
    What are the rules and limitations when using optional elements in tuples?
    Consider the order and presence of elements in tuples.
    You got /4 concepts.