0
0
Typescriptprogramming~5 mins

Tuple with fixed length and types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a tuple in TypeScript?
A tuple is a fixed-length array where each element has a specific type. It allows you to store multiple values of different types in a single variable.
Click to reveal answer
beginner
How do you declare a tuple with a fixed length of 3 elements: a string, a number, and a boolean?
You declare it like this: <pre>let myTuple: [string, number, boolean];</pre> This means the tuple must have exactly three elements in that order and type.
Click to reveal answer
intermediate
Can you change the length of a tuple after it is declared?
No, tuples have a fixed length defined by their type. You cannot add or remove elements beyond the declared length without causing a type error.
Click to reveal answer
beginner
What happens if you try to assign a wrong type to a tuple element?
TypeScript will show a type error because each position in the tuple expects a specific type. For example, assigning a string to a number position is not allowed.
Click to reveal answer
beginner
Example: How to access the second element of a tuple [string, number, boolean]?
You access it by index like an array:
myTuple[1]
which will give you the number value because indexes start at 0.
Click to reveal answer
What does the tuple type [string, number] mean?
AA function returning string and number
BAn array with exactly two elements: first a string, second a number
CAn object with string and number properties
DAn array with any number of strings and numbers
Can you assign ["hello", 42, true] to a variable typed as [string, number, boolean]?
ANo, because booleans are not allowed
BNo, because the length is wrong
CYes, but only if you use type assertion
DYes, because the types and order match
What happens if you try to push an extra element to a tuple?
ATypeScript will give a type error
BThe tuple will accept it without error
CThe tuple will convert to an array
DThe extra element will be ignored
How do you declare a tuple with two elements: a boolean and a string?
Alet t: [boolean, string];
Blet t: (boolean | string)[];
Clet t: boolean & string;
Dlet t: {boolean, string};
Which index accesses the first element of a tuple?
A1
B-1
C0
DIt depends on the tuple
Explain what a tuple with fixed length and types is in TypeScript and why it is useful.
Think about a small box with fixed slots for different items.
You got /4 concepts.
    How do you declare and use a tuple with three elements: string, number, and boolean? Give an example.
    Remember tuples are like arrays but with fixed types and length.
    You got /4 concepts.