We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Optional Elements in Tuples

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"];

Optional Values Are Last

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];

Optional Types Are Potentially Undefined

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.

Assignment

  • #3 Send a dog
  • #4 Give me my tuna! [REFUND]