Types and inference

Type arrays

Describe a collection whose elements share a type and understand the equivalent bracket and generic syntax.

An array type answers one question: what can each element be? Both forms describe an array of strings:

const names: string[] = ['Ada', 'Lin']
const moreNames: Array<string> = ['Grace']

string[] and Array<string> mean exactly the same thing. The bracket form is shorter and more common. The generic form reads better when the element type is itself complex, like Array<string | number>.

The element type guards every operation

TypeScript checks values added later:

names.push('Margaret')
names.push(42)

The first call works. The second one fails with:

Argument of type 'number' is not assignable to parameter of type 'string'.

The check protects reads too. Every element you pull out of names is a string, so string methods are always safe on it.

Inference flows through array methods

Array methods receive the element type through inference:

const uppercaseNames = names.map(name => name.toUpperCase())

You did not annotate name, but TypeScript knows it is a string because names is a string[]. It also infers the result as string[], since toUpperCase() returns a string. Chain a .filter() or another .map() after it and the types keep flowing.

Mixed elements need a union

Use a union only when mixed elements are intentional:

const ids: Array<string | number> = ['a1', 42]

Now each element is string | number, so reading an element gives you a value you must narrow before calling type-specific methods on it. That extra step is the honest price of a mixed collection.

One mistake to avoid

Do not widen an array to any[] just to make one bad insertion compile. That removes useful checking from every later read: names[0].toUppercase() with a typo would compile fine and crash at runtime. If TypeScript rejects a push, the element type is telling you something about your data. Fix the value or widen the union deliberately.

Exercise: create a number[], map it to formatted strings, and hover over the result type.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →