Skip to main content

Command Palette

Search for a command to run...

Arrays vs Tuples in TypeScript

Updated
0 min read
Arrays vs Tuples in TypeScript
O

Hi there 👋🏾. I'm a software engineer that enjoys building stuff and talking about them. I also tinker a bit with hardware and robotics using Arduino and ROS.

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.

P

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 :

https://www.javatpoint.com/typescript-tuples

More from this blog

O

Osinachi's base

66 posts

Hi there, I'm a software engineer that enjoys building stuff and talking about them. I also tinker a bit with hardware and robotics using Arduino and ROS.