

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Tuples
incomplete
2: Readonly
incomplete
3: Tuples vs. Objects
incomplete
4: Destructuring Tuples
incomplete
5: Named Tuples
incomplete
6: Optional Elements in Tuples
incomplete
7: Tuple Rest Elements
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Like object properties, you can make tuple elements optional using the ? modifier:
type HttpResponse = [statusCode: number, data: string, error?: string];
// Both of these work!
const successResponse: HttpResponse = [200, "Success!"];
const errorResponse: HttpResponse = [404, "", "Resource not found"];
Similar to optional function parameters, all required elements must come before optional elements. This does not work:
type HttpResponse = [statusCode: number, data?: string, error: string];
But this does:
type HttpResponse = [statusCode: number, data?: string, error?: string];
All optional elements are automatically unioned with undefined.
type UserInfo = [name: string, age: number, address?: string];
function handleUserInfo(user: UserInfo) {
const [name, age, address] = user;
// name: string
// age: number
// address: string | undefined
}
Personally when I have a bunch of optional properties, I prefer to just use an object type most of the time. I'm less worried about length checks and such with objects.
#3 Send a dog#4 Give me my tuna! [REFUND]