Reuse a type

INPUT · Slides

Read the angle brackets

01 / 05

Angle brackets are harmless once you can read them

By now you can put types on variables, arrays, functions, objects and classes. Let us finish by clearing up one thing that always turns up when you read other people's code.

It is a type with angle brackets on it, like Array<string>. Startling the first time you see it — but the contents are something you already know.

02 / 05

What Array<string> really is

To give away the answer: it means "an array that holds strings".

Which is to say, exactly the same as the string[] you wrote in chapter 1. One thing, two ways of writing it.

const colors: Array<string> = ["red", "blue"];console.log(colors);

Result

["red", "blue"]

03 / 05

What is inside the brackets is an argument to a type

Just as a function takes values inside its brackets, a type sometimes takes a type inside its angle brackets.

Think of Array as a tool for making an array type. Hand it number and out comes an array of numbers. Change what you hand over and you get a different array type.

const scores: Array<number> = [80, 65, 92];console.log(scores.length);

Result

3

04 / 05

Anything that does not match will not go in

An array written as Array<number> will only take numbers. Try to slip a string in and it stops you, just as before.

The angle brackets only changed how it looks. What it does is no different from the array types you wrote in chapter 1.

const prices: Array<number> = [120, "80"];

Result

Type error: Type 'string' is not assignable to type 'number'.

05 / 05

Either way of writing is fine

They mean the same thing, so write whichever you like. The shorter one gets used more day to day, but you will come across the angle brackets too.

What matters is being able to read both. From here you write the angle-bracket form yourself, to get your eye used to it.

const a: Array<string> = ["Yui"];const b: string[] = a;console.log(b);

Result

["Yui"]