FewV minutes of Arrays and Tupple in Typescript.
» Arrays in TypeScript
-
For Arrays in TypeScript, We have a specific syntax for typing out an array.
-
And that is as follows
const names: string[] = ["John", "Jane", "Mary"];
const ages: number[] = [25, 30, 27];
Console:
["John", "Jane", "Mary"]
[25, 30, 27]
-
names is a variable which has a type of string and the square brackets means the variable names is an array containing various values like John, Jane, Mary.
-
Similarly, ages is a variable which has a type of number and the square brackets means the variable ages is an array containing various values like 25, 30, 27.
-
Now if we want to add a value in names or ages we can do it with push property.
const names: string[] = ["John", "Jane", "Mary"];
const ages: number[] = [25, 30, 27];
names.push("Bob"); //adding Bob in names array
ages.push(10); //adding 10 in ages array
Console:
["John", "Jane", "Mary", "Bob"]
[25, 30, 27, 10]
» Readonly Arrays in TypeScript
-
Now what if we want arrays to remain unchanged, for this we have readonly keyword, which will prevent array from being changed.
-
It is typed as
// Readonly array
const books: readonly string[] = ["Harry Potter", "Lord of the Rings"];
- And now if we try to add another book in books variable, TypeScript will throw an error.
books.push("Almond"); //error => Property 'push' does not exist on type 'readonly string[]'
» Type infer in Arrays
- TypeScript can also infer (guess) the type of an array based on it’s value.
// Array type inference
let myFavBooks = ["Harry Potter", "Lord of the Rings"];
// TypeScript infered the type of myFavBooks to string.
- But what if we by mistakenly change the type of myFavBooks, TS will throw error.
myFavBooks.push(21);
//error => Argument of type 'number' is not assignable to parameter of type 'string'.
- Which means we cannot use any other type than what is already infered by TS at first.
» Tuple in TypeScript.
-
A tuple is a typed array with a fixed length and fixed types for each index.
-
To define a tuple, we have to specify the type of each element that is in the array.
let ourTuple: [string, number];
ourTuple = ["John", 25];
Console:
["John", 25]
- But when we add an extra value, we will get error
let ourTuple: [string, number]; //target
ourTuple = ["John", 25, true]; //source
// error => Type '[string, number, boolean]' is not assignable to type '[string, number]'.
// Source has 3 element(s) but target allows only 2.
- So it is very important to know that the source and target element matches, not only in length but also in each element type.
Thank You, I hope this clears Array and Tupple in TypeScript.