Arrays vs Tuples in TypeScript

Arrays vs Tuples in TypeScript

ยท

0 min read

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

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

Doing this also throws and error

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

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

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

const nameAge: [string, number] = ['Osinachi', 10011];

Same as arrays

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

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 their 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.

ย