ARRAY AND TUPLES IN TYPESCRIPT - DAY4 OF #100DAYSOFCODE
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
ARRAY IN TYPESCRIPT
In typescript, typescript need to know type of each items in array. so it will tell us error if we are modify, or perform some actions in array/item of array.
Above we have different user. if we don't mension type and if there is any item in array then typescript will auto assume type based on typeof array. in above example all value is string so type of this array is string[]( square bracket [] after typeof item for single dimentsional array).
If we don't give value to array , then it will take type any[]. But we should not allowed any type. for more about any type visit this
We also give explicit type by type annotations in array like below. if you don't know type annotation then read my this previous blog
For two dimensional array , we have to give two bracket after item type like below,
Why we need to give type to array ?
we are doing lot's of manipulation to the array like adding a new elements, changing the value of an item of the array, apply some methods to the items. so we need to be aware of that. let's understand by examples
领英推荐
We can give multiple types to the same array, but we can see in the future. now let's understand tuples.
What is tuple?
Sometimes we want key-value only. as we can't give the key to array in js we need to make an object for this. but for only 2 things, it is also not suitable to make object. right!!!
a tuple is a solution for this. tuple allowed us to express an array with a fixed size of length, whose types are the same but not known but don't need to same. let's say you want to store user id and email only. you can make either object or make tuple for this as shown below. but tuple is suitable more for this type of example.
The order of id and email should always be the same for each tuple, so we can know that the first element will always be id and the second will always email. you can not reverse. it will give an error.
const userUsingTuple: [number, string] = [1000, "[email protected]"];
userUsingTuple[0] = '[email protected]'
// you can't change type of element. it will give Type 'string' is not assignable to type 'number'
const userUsingTuple1: [number, string] = ["[email protected]", 1001]
// Type 'string' is not assignable to type 'number'.
Let's see more examples with different lengths of tuples.
Generally, we use a tuple when we do not want to create the object because of a few numbers of key-value pairs.
The difference between an array in a tuple