Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Array Typing | Arrays
Introduction to TypeScript
course content

Зміст курсу

Introduction to TypeScript

Introduction to TypeScript

1. TypeScript Fundamentals
2. Conditional Statements
3. Arrays
4. Loops
5. Functions

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

12
let mixedArray: (number | string)[] = ['apple', 1, 'banana', 2]; console.log(mixedArray);
copy

We used 2 different types when declaring the array. We mixed numbers and fruits.
Why?
I don't know.

What is the correct syntax used to define an array with multiple types?

What is the correct syntax used to define an array with multiple types?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 3
some-alt