Array & Tuple Type By albro
Usually, in Typescript, two types of arrays are considered: flexible and hard.
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking']
};
I have added another attribute called hobbies
to the object and I have put two values of sports
and cooking
in the form of an array. If you move your mouse over hobbies
, its type will be displayed:
As you can see, the type of this array is []string
! We have never seen such type before. This syntax is the typescript method to specify the type of arrays: first we have the []
sign and then we have the type of data stored in the array, which in this example is String
because the values in hobbies
are strings
.
For example, suppose we define a new variable and want to specify its type:
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking']
};
let favoriteActivities: string[];
As you can see, the favoriteActivities
variable is defined, but I have not set its value and I have only specified its type. This code tells us that the value inside favoriteActivities
must be an array first, then a string
second, so the following code will encounter an error:
let favoriteActivities: string[];
favoriteActivities = 'Sports';
why Because sports
is just a string
and not an array
. To solve this problem, we can convert it into an array
:
let favoriteActivities: string[];
favoriteActivities = ['Sports'];
Also, if we add a number to this array, we will encounter an error:
let favoriteActivities: string[];
favoriteActivities = ['Sports', 1];
Because the new value is an array, but it is no longer a string, but has a number inside it. One of the ways to get rid of this error is to change the array type:
let favoriteActivities: any[];
favoriteActivities = ['Sports', 1];
Doing this removes the error, but we lose all the benefits of TypeScript! Why? any
data type means anything can be placed in this field (string
, number
, array
, etc.). On the other hand, one of the main purposes of typescript is to add type or data type, and if we use any
, it is practically as if we have used javascript and we don't need typescript anymore. You should know that any
is a special type that has very specific uses and in most cases you should avoid it as much as possible so as not to lose the benefits of typescript.
Now suppose we want to go through hobbies
with a for
loop and console.log
its values. We can simply say:
for (const hobby of person.hobbies) {
console.log(hobby);
}
So far, we have written our own JavaScript and have not done anything special. If we run tsc app.ts
now, we get two values Sports
and Cooking
in the browser console. The interesting thing about TypeScript is that we can use any string method on hobby
in the above code:
TypeScript understands that if hobbies
is an array
and type is a string
array, then each member of it (hobby
) will be a simple string
and prepares the methods. With this account, this code is correct:
for (const hobby of person.hobbies) {
console.log(hobby.toUpperCase());
}
But the following code is no longer correct:
for (const hobby of person.hobbies) {
console.log(hobby.map()); // !!! ERROR !!!
}
Why? Because TypeScript knows the type of hobby
variable and understands that hobby
is not an array
, so the map
method that is called on arrays does not match with it and underlines map
as an error.
What is a tuple?
Every type we have learned so far is supported by JavaScript itself and is nothing new (of course, only at the level of understanding and recognition), but let's move on to types that are not available in JavaScript. The first one is Tuple
. Tuple
s are present in some other programming languages such as Python, but not in JavaScript. An example of tuple
s is as follows:
[1,2]
You are probably saying to yourself that this is an array! You are right. Tuple
s are actually arrays of fixed length and type. Let me show you how to use them. Suppose we add another feature to the same example:
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: [2, 'author']
};
Suppose that the role
attribute is supposed to determine the level of access and responsibility of people on our site. For example, in the code above, we have assumed that the number 2
is equal to the author
level, and people of this level can write articles on our site. The numerical part is for use in checking operations on the server side, and the author
part is for display on the front-end of the site so that users can understand the status of each person
. Such an array must always have two members, the first being a number
and the second being a string
.
If you move the mouse over the role
right now, you will see its type:
We have not seen this type before. We call this type of type union type
, which combines several special types together. The important thing here is that Typescript realizes that role is an array that takes two types of numbers
and strings
.
Unfortunately, we can now run the following command:
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: [2, 'author']
};
person.role.push('admin');
With the above statement, our array takes three members. The following code is also completely correct:
const person = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: [2, 'author']
};
person.role.push('admin');
person.role[1] = 10;
That is, we can replace the first index (second member) with a number! Unfortunately, TypeScript does not recognize that this is not what we want. Why? Look again at the role
type:
The role
type just says that this is an array
and the values inside can be numbers
or strings
. We have not specified the number
, nor whether any type of member is the first member or the second member. Tuple
s are great for this kind of problem!
This is where we can use tuples and specify the role
type manually:
const person: {
name: string;
age: number;
hobbies: string[];
role: [number, string];
} = {
name: 'Maximilian',
age: 30,
hobbies: ['Sports', 'Cooking'],
role: [2, 'author']
};
When we use this structure (ie [number, string]
), we tell Typescript that this value is a tuple
, so it has only two members. We also declare that the first member must be a number
and the second member must be a string
. This is one of the few cases where specifying the type manually is not prohibited and you can use it (of course, you will not make an error in other situations, but overwrite). With this account, if we write the following code, we will encounter an error:
person.role[1] = 10;
But the following code runs without error:
person.role.push('admin');
The reason is that push
is an exception. The push
statement is allowed exceptionally in tuples and you can use it. So TypeScript can't catch this error. Of course, the following code will be an error:
person.role = [0, 'admin', 'user'];
Because we have declared that the role
will have only two members, but here we have passed three members. Remember that only push
is an exception, but the rest are detected.
[@PowerPaul:]
Buddy! The @CryptoCompany Voting Service and its trail were here!
Thank you for your support & Hive a great day!
You like to support CryptoCompany?
Check out, reblog or vote some postings from the last 7 days about the CryptoCompany universe:
• [ENG/DEU] Bro Bang Event 7 is over, 8 has started + EVENT & SEASON RANKINGS
Congratulations!
✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪
♟ We invite you to use our hashtag #chessbrothers and learn more about us.
♟♟ You can also reach us on our Discord server and promote your posts there.
♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.
♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.
🥇 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.
Kindly
The CHESS BROTHERS team
Congratulations!
✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪
♟ We invite you to use our hashtag #chessbrothers and learn more about us.
♟♟ You can also reach us on our Discord server and promote your posts there.
♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.
♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.
🥇 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.
Kindly
The CHESS BROTHERS team
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.
Excellent post. What the heck is up with all these bots tho?