0
0
Typescriptprogramming~5 mins

Tuple type definition in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a tuple type in TypeScript?
A tuple type in TypeScript is an array with a fixed number of elements where each element can have a different type. It defines the exact types and order of elements.
Click to reveal answer
beginner
How do you define a tuple type with a string and a number in TypeScript?
You define it like this: <code>let example: [string, number];</code> This means the first element must be a string and the second a number.
Click to reveal answer
intermediate
Can tuple elements be optional in TypeScript? How?
Yes, tuple elements can be optional by adding a question mark after the type. Example: <code>let example: [string, number?];</code> means the second element can be a number or undefined.
Click to reveal answer
beginner
What happens if you try to assign wrong types to a tuple in TypeScript?
TypeScript will show an error because tuples expect specific types in a fixed order. For example, assigning a number where a string is expected will cause a type error.
Click to reveal answer
advanced
How can you use rest elements in tuple types?
You can use rest elements to allow a variable number of elements of the same type at the end. Example: <code>let example: [string, ...number[]];</code> means one string followed by any number of numbers.
Click to reveal answer
How do you declare a tuple with a boolean and a string in TypeScript?
Alet t: [boolean, string];
Blet t: (boolean | string)[];
Clet t: boolean, string;
Dlet t: {boolean, string};
What is true about tuple types in TypeScript?
AThey have fixed length and fixed types per position.
BThey can only contain elements of the same type.
CThey are the same as arrays.
DThey cannot have optional elements.
How do you make the last element of a tuple a variable number of strings?
Alet t: [number, string?];
Blet t: [number, string];
Clet t: [number, ...string[]];
Dlet t: [number, string[]];
What error occurs if you assign [42, 'hello'] to let t: [string, number]?
ASyntax error.
BNo error, assignment is valid.
CRuntime error only.
DType error because the first element should be string, not number.
Can tuple types have optional elements in TypeScript?
AOnly the first element can be optional.
BYes, by adding a question mark after the type.
CNo, tuples must always have all elements.
DOptional elements are only for arrays.
Explain what a tuple type is in TypeScript and how it differs from a regular array.
Think about how many elements and what types each element can have.
You got /4 concepts.
    Describe how to define a tuple with optional and rest elements in TypeScript.
    Consider how to allow some elements to be missing or repeated.
    You got /3 concepts.