Typescript: Array & Tuples
Tags: typescript, webdev, beginners, tutorial
Published: 2023-02-08 12:26:16


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:

```ts
let variableName: arrayType[] = []

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

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:

```ts
// ❌ 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({})
```

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

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

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.

```ts
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]);
```

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:

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

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

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:

```ts
let x: [number, string];

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

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

```ts
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
```

**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:

```ts
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.
```

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 |
|--|--|--|--|--|--|--|
| [![](https://cdn-icons-png.flaticon.com/32/4494/4494477.png)](https://twitter.com/j471n_) |[![](https://cdn-icons-png.flaticon.com/32/2504/2504911.png)](https://github.com/j471n) |  [![](https://cdn-icons-png.flaticon.com/32/3536/3536505.png)](https://www.linkedin.com/in/j471n/)|[![](https://cdn-icons-png.flaticon.com/32/174/174855.png)](https://instagram.com/j471n_)| [![](https://cdn-icons-png.flaticon.com/32/3178/3178285.png)](https://j471n.in)| [![](https://cdn-icons-png.flaticon.com/32/5822/5822078.png)](https://www.getrevue.co/profile/j471n) | [![](https://cdn-icons-png.flaticon.com/32/2935/2935413.png)](https://www.buymeacoffee.com/j471n)|