Arrays vs Tuples in TypeScript

Subscribe to my newsletter and never miss my upcoming articles

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.

Comments (1)

Purvi Barot's photo

Tuple : A tuple is a grouping of unnamed, ordered values. Each value in a tuple does not need to be the same type.

 const tuplename : [string, number] = [ "ABC", 12 ]

Array : An array is mutable collection. They are very efficient to create, but must always be a single type.

const arrayname: [string] = ["A", "B", "C"]

For more information,refer the following link :