...

/

Creating a strongly-typed array

Creating a strongly-typed array

We will learn how to create strongly-typed arrays at the start of this lesson. We will use two different methods to achieve this before learning how to create strongly-typed rest parameters.

Arrays can hold mixed value types #

Before we learn how to create a strongly-typed array, let’s look at an array that has been declared without a type annotation. The code below constructs an array containing three different values, each with a different type.

const items = [];
items.push(1);
items.push("two"),
items.push(false);
console.log(items);

Why doesn’t the code above raise a type error?

Using the Array generic type #

We can use a type annotation to specify that an array should only contain items of a specific type. There is an Array generic type that we can use to do this. We pass ...