DEV Community

Cover image for Typescript: Array & Tuples
Jatin Sharma
Jatin Sharma

Posted on • Edited on

Typescript: Array & Tuples

In this article, We are going learn about how you can use type in Array and there is a special thing that is Read only Array. In which you can't manipulate the values. In addition, I'll talk about Tuples as well. How you can use it?

This is going to be a full series of typescript where you will learn from basic topics like string, boolean to more complex like Type Aliases, enums, Interface, generics, and etc.

Arrays

To create an Array of a certain type there is a special syntax for that:



let variableName: arrayType[] = []

// For example: 
let num: number[] = [1,2,3]
let name: string[] = ["sam", "john"]


Enter fullscreen mode Exit fullscreen mode

As shown in the above example that you can define the array's type by using the type followed by square brackets (number[])

This is simple right? Let's look at some other concepts. Let's look at the Dos and Don'ts of an Array:



// ❌ DON'T 
// If you define an array like this then the type will be 'never'
// which means you can't push anything
let num:[] = []
num.push(1) // ERROR


let num:number[] = []
num.push(1)
num.push("232")  // ❌ ERROR : rgument of type 'string' is not assignable


let names:string[] = []
names.push("john")
names.push(1)   // ❌ ERROR : rgument of type 'number' is not assignable

/* -----------Let's Add Objects into Array-------- */
type User ={
    name: string,
    email: string,
}

// ✅ That's how you can define an array of objects
const allUsers: User[] = [];

// ✅ CORRECT
allUsers.push({name: "sam", email:"sam@hello.com"})
// ❌ ERROR: email property missing
allUsers.push({name: "sam"})
// ❌ ERROR: missing name & email
allUsers.push({})


Enter fullscreen mode Exit fullscreen mode

The above example shows how you can use Array. There is one more way to create an Array:



let newArray: Array<number> = []
let nameArray: Array<string> = []
let allUsers: Array<User> = []


Enter fullscreen mode Exit fullscreen mode

It means that creating an Array of the defined type in <>.

Readonly Array

The ReadonlyArray is a special type that describes arrays that shouldn’t be changed.



let players: ReadonlyArray<string> = ["ronaldo", "messi"]
// or
let  players: readonly string[] = ["ronaldo", "messi"];  

// ❌ Can't do that
players[0] = "jordon";
players.push("shaq")

// ✅ Can do 
console.log(players[0]);


Enter fullscreen mode Exit fullscreen mode

In the above code, there are two methods from which you can define the readonly Array.

At the End of this section, I want to add one more thing to this. What if we want a nested Array means Array inside an array? You can do that as shown in the following code:



const cords: number[][] = [
    [22, 55],
    [45, 22]
]

const data: number[][][] = [
    [[22], [25, 65]],
    [[99, 34, 56], [12, 9]],
]


Enter fullscreen mode Exit fullscreen mode

You can define the nested array as shown in the above code. You can nest as many arrays as you want. And if you want them to be different types then you need to create a type for them.

Tuples

Tuple types are a type of array of known length where the different elements may have different types. A value of type [number, string] is guaranteed to have a length of 2, with a number at element 0 and a string at element 1. Let's look at the example:



let x: [number, string];

x = [110, "Mohan"]; // ✅ CORRECT 
x[0] = 120; // ✅ CORRECT 
x = ["Mohan", 110]; // ❌ ERROR: Initialize it incorrectly


Enter fullscreen mode Exit fullscreen mode

Let's take another example of RGB. As you already know RGB takes three values that should be numbered.



let rgb: [number, number, number];

rgb = [225, 224, 10];       // ✅ CORRECT
rgb = [225, 224, "10"];     // ❌ ERROR: type 'string' is not assignable to type 'number'
rgb = [225, 224, 10, 40];   // ❌ ERROR : Source has 4 element(s) but target allows only 3


Enter fullscreen mode Exit fullscreen mode

Issue with Tuples

Tuples sound great right? But they have a major flaw. TypeScript allows you to call methods like push(), pop(), shift(), unshift(), and splice() on values of tuple types.

If you don't understand what I am saying then let me show you with code example. I am taking the old example of RGB:



let rgb: [number, number, number];

// ✅ This is correct because it has all the values
rgb = [225, 224, 10];

// ❌ ERROR : Source has 4 element(s) but target allows only 3
// It is not allowed Right.
rgb = [225, 224, 10, 40];   

// Now let's do this:
rgb.push(50)
console.log(rgb)  // output: [225, 224, 10, 50]
// This is the flaw.


Enter fullscreen mode Exit fullscreen mode

You can apply any Array method to Tuple. That's why it destroys the supposed guarantees of tuple types.

Don't only rely on Tuples. Use only when necessary.

Wrapping up

In this article, I explained how you can use type in Array and there is a special thing that is Read only Array. In which you can't manipulate the values. In addition, I also talked about Tuples as well and how you can use them?

This is a series of Typescript that will help you to learn Typescript from the scratch. If you enjoyed this article, then don't forget to give ❤️ and Bookmark 🏷️for later use and if you have any questions or feedback then don't hesitate to drop them in the comments below. I'll see in the next one.

Connect with me

Twitter GitHub LinkedIn Instagram Website Newsletter Support

Top comments (8)

Collapse
 
ant_f_dev profile image
Anthony Fung

Great article!

I'd like to mention a side note. Using const when declaring variables is a great way to avoid accidentally overwriting it in a function. One thing that I've seen some people miss is that an array can be declared as const and it can still be pushed to - being const just means overwriting it will cause an error, but it can still be mutated.

Collapse
 
j471n profile image
Jatin Sharma

Yes you can manipulate a const array through various methods. However, you cannot reassign that array (it's elements can be reassigned).

Collapse
 
vinsay11 profile image
Winsay vasva

Good Article Man......intresting

Collapse
 
j471n profile image
Jatin Sharma

Thanks 😊

Collapse
 
lotfijb profile image
Lotfi Jebali

Insightful 😁

Collapse
 
j471n profile image
Jatin Sharma

Thanks Lotfi. 😊

Collapse
 
atinypixel profile image
Aziz Kaukawala • Edited

Got to know something new about Arrays and Tuples!
Thanks Jatin

Collapse
 
j471n profile image
Jatin Sharma

I am glad you find it useful 😊