Зміст курсу
Introduction to TypeScript
Introduction to TypeScript
Array Typing
TypeScript is known for its type system. That's why it's called TypeScript.
© The Author of this course
In previous chapters, we've already seen how to type arrays.
But first, let's answer one question: why do we even need typing for arrays?
Let's take an example of a bookshelf. We buy a bookshelf and start putting various books on it. But as time goes by, we start putting other random items there as well, like medals, cups, boxes, and so on. Eventually, our bookshelf stops being just a bookshelf and becomes a regular shelf.
This is where typing comes in. If we decide that our bookshelf should only contain books, we specify that as the type.
For example:
So, we've defined that the bookshelf will exclusively contain books.
Note
There is no such type as
book[]
; I made it up to make the example more understandable.
If you've bought a bookshelf not just for books but also for figurines, for example, then you can type the bookshelf
array with multiple data types, like this:
So, we've defined that the bookshelf
will store not only books but also figurines.
We can do the same with a real-world case when creating an array. For example, we need to store numerical values and strings, like this:
let mixedArray: (number | string)[] = ['apple', 1, 'banana', 2]; console.log(mixedArray);
We used 2 different types when declaring the array. We mixed numbers and fruits.
Why?
I don't know.
Дякуємо за ваш відгук!