Arrays vs. tuples in TypeScript

Difference between Arrays and Tuples in TypeScript

TypeScript offers JavaScript developers a robust solution to writing bug-minimal code. It offers more types and stronger type-checking than JavaScript. We’ll be exploring tuples and arrays in TypeScript.

Typically, a tuple is an array with fixed size and known datatypes. This is to say; you’d use a tuple for a static, well-defined array.

Let’s have an example

We have a tuple of primary colors with known values:

const primaryColors: [string, string, string] = ['#ff0000', '#00ff00', '#0000ff'];
console.log(primaryColors);

If we exclude one string in the definition of types, we get an error. If we don’t include all three primary colors​, we also get an error, i.e., doing this throws an error:

const primaryColors: [string, string] = ['#ff0000', '#00ff00', '#0000ff'];
// throws an error because there's an extra string

Doing this also throws and error:

const primaryColors: [string, string, string] = ['#00ff00', '#0000ff'];
// throws an error because all strings have not been provided

Using an array instead

If we were to store the same data in an array, we’d simply do this:

const primaryColors: string[] = ['#ff0000', '#00ff00', '#0000ff'];
console.log(primaryColors);

Note: We can also store a combination of datatypes in a tuple. Here’s an example:

const nameAge: [string, number] = ['Osinachi', 10011];
console.log(nameAge);

Same goes for arrays:

const nameAge: (string | number)[] = ['Osinachi', 10011];
console.log(nameAge);

The structure of the tuple needs to stay the same (a string followed by a number), whereas the array can have any combination of the two types specified (this can be extended to as many types as is required).

const nameAge: (string | number)[] = ['Osinachi', 10011, 12345, "Victor"];
console.log(nameAge);

Why do we need tuples?

We need them to store data in an unchanging array, e.g., an employee’s personal information.

So, tell me other uses of tuples you’ve come across. If you’ve never used TypeScript, check out its docs here. If you want an interesting introduction, check out this shot on TypeScript.

Thanks for reading. Let’s connect on Twitter and LinkedIn.