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

Tuples

A tuple is a special kind of array where each position has a specific, known type.

const nameAndAge: [string, number] = ["Rose Tyler", 24];

The existence of tuples in TypeScript has me using them where I never would have used an array in JavaScript. The fact that the length is fixed and the type of index is known makes them much more safe to use for small collections.

Be Explicit With Tuples

You need to provide explicit typing with tuples! This is a tuple:

// [string, number]
const nameAndAge: [string, number] = ["John Jones", 104];

But if we remove the type, it's inferred as an array of string | number:

// (string | number)[]
const nameAndAge = ["Martha Jones", 24];

With a (string | number)[] you can do this:

const nameAndAge = ["Martha Jones", 24];
nameAndAge[1] = "Donna Noble";

But with a tuple, TypeScript will provide an error (which is probably what you want). So, always explicitly type your tuples!

const nameAndAge: [string, number] = ["Martha Jones", 24];
// Error: Type 'string' is not assignable to type 'number'.
nameAndAge[1] = "Donna Noble";

Assignment

Support.ai is adding support ticket automation. We need each ticket to be a sequence of data types.

Complete the createTicket function. It takes a prevTicket number and comment string as inputs and returns a tuple.

Tips

  • The toLowerCase() method can be used to convert a string to lowercase.
  • The includes() method can be used to check if a string contains a substring.