DEV Community

Cover image for Arrays vs Tuples in TypeScript
Osinachi Chukwujama
Osinachi Chukwujama

Posted on

Arrays vs 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'd explore 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'];
Enter fullscreen mode Exit fullscreen mode

If we exclude one of the string in the definition of the types, we get an error. If we don't include all three primary colours, we also get an error. i.e
Doing this throws an error

const primaryColors: [string, string] = ['#ff0000', '#00ff00', '#0000ff'];
// throws an error
Enter fullscreen mode Exit fullscreen mode

Doing this also throws and error

const primaryColors: [string, string, string] = ['#00ff00', '#0000ff'];
// throws an error
Enter fullscreen mode Exit fullscreen mode

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'];
Enter fullscreen mode Exit fullscreen mode

Note: We can also store other datatypes in a tuple. Here's an example.

const nameAge: [string, number] = ['Osinachi', 10011];
Enter fullscreen mode Exit fullscreen mode

Same as arrays

const nameAge: (string | number)[] = ['Osinachi', 10011];
Enter fullscreen mode Exit fullscreen mode

Why do we need tuples?

To store data in an unchanging array.

So, tell me other uses of tuples you've come across. If you have never used TypeScript, check out the docs here. If you want an interesting introduction, check out this Scrimaba tutorial on TypeScript.

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

Discussion (0)