Sub topic 1
Typing arrays with T[] and Array<T>
Prerequisites
This chapter assumes you know the following:
- JavaScript arrays and methods such as
push,mapandfilter. - Basic TypeScript annotations, such as
const n: number = 1. - Union types such as
string | number. - Generic syntax like
Promise<string>. You don't need to write generics yourself.
The examples assume strict mode is on, which is the default in a new tsc --init project.
Two spellings of one type
TypeScript has two ways to write "an array whose elements are all of type T":
const scores: number[] = [90, 85, 72];
const names: Array<string> = ["Ada", "Linus"];number[] is shorthand for Array<number>. The compiler treats them as the same type. Array<T> is the global generic interface declared in TypeScript's standard library, and T[] is syntax sugar for it. Neither is faster, safer or more strict than the other.
Pick one spelling and use it consistently. Most codebases use T[] for simple element types and Array<T> when the element type is long or complex. The @typescript-eslint/array-type lint rule can enforce a choice for you. Its array-simple option applies exactly this convention.
interface User {
id: number;
name: string;
}
const users: User[] = [{ id: 1, name: "Ada" }];
const handlers: Array<(event: string) => void> = [
(event) => console.log(`first: ${event}`),
(event) => console.log(`second: ${event}`),
];
handlers.forEach((handler) => handler("click"));The Array<...> form in the second declaration avoids the parentheses that the shorthand would need, as the next section shows.
Element types that need care
The [] suffix binds tighter than | and =>. That is the source of most array-annotation mistakes.
const a: (string | number)[] = ["a", 1]; // array whose elements are string or number
const b: string | number[] = "a"; // either one string, or an array of numbers
const c: Array<string | number> = ["a", 1]; // same type as aWithout parentheses, string | number[] means "a string, or an array of numbers". Assigning ["a", 1] to b is an error. Inside Array<...> you need no parentheses, because the angle brackets group the union for you.
Function types have the same trap:
type Getter = () => string;
const getters: Getter[] = [() => "a", () => "b"]; // array of functions
const inline: (() => string)[] = getters; // same, written inline
type MakeList = () => string[]; // one function that returns an array() => string[] is a function that returns a string array. (() => string)[] is an array of functions. When you see a type error you can't explain, check where the parentheses sit.
Nested arrays
Add one [] for each level of nesting. Each level is its own array type:
const grid: number[][] = [
[1, 2, 3],
[4, 5, 6],
];
const cell: number = grid[1][2]; // 6
const rows: Array<Array<number>> = grid; // identical typeRows in a number[][] can have different lengths. The type says nothing about size. If you need a fixed shape, such as exactly two numbers per row, you want a tuple, which a later chapter covers.
Empty arrays
An empty literal gives the compiler nothing to infer from, so it is better to annotate it:
const queue: string[] = [];
queue.push("job-1");
// queue.push(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.If you leave off the annotation under noImplicitAny, TypeScript uses an "evolving array type". The element type starts as unknown and is refined by each push:
const evolving = [];
evolving.push(1);
evolving.push(2);
const total = evolving[0] + evolving[1]; // evolving is number[] hereThis works only while the compiler can follow the assignments in a straight line. If you read the array before any push, or pass it into a closure, you get an implicit-any error. Relying on it also makes the type hard to see when you read the code. An annotation like const queue: string[] = [] is clearer, and it is the form you want for exported variables and function return types.
What the element type constrains
The element type applies to everything you read from or write to the array:
const ids: number[] = [10, 20, 30];
ids.push(40); // OK
const doubled = ids.map((id) => id * 2); // number[]
const label = ids[0].toFixed(1); // OK: ids[0] is number
// ids.push("50"); // Error: string is not assignable to numberMethods are typed from the element type. map returns an array of whatever the callback returns, and find returns T | undefined. A later chapter covers methods in detail.
Arrays are objects, so typeof ids is "object" at runtime. To check for an array at runtime, use Array.isArray. TypeScript treats it as a type guard:
function toList(input: string | string[]): string[] {
if (Array.isArray(input)) {
return input; // narrowed to string[]
}
return [input]; // narrowed to string
}
console.log(toList("a"), toList(["b", "c"]));One gotcha: when the declared type is unknown or any, Array.isArray narrows to any[], not to your intended element type. After the check, validate the elements yourself.
Assignability and its limits
An array type is assignable to another when the element types are assignable. This is called covariance:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
class Cat extends Animal {
meow() {
return "meow";
}
}
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs; // allowed
animals.push(new Cat()); // compiles, but dogs now contains a Cat
console.log(dogs[1].bark()); // runtime error: dogs[1].bark is not a functionThe compiler accepts this even though it is unsound. Two names point at the same array, and animals allows writes that dogs does not expect. TypeScript trades some safety here for convenience, because rejecting it would make common code painful.
If a function only reads from an array, say so in its parameter type. A readonly Animal[] parameter cannot be written through, so passing Dog[] into it is safe. The Readonly arrays chapter covers this.
Common errors
| Symptom | Cause | Fix | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `Type 'string' is not assignable to type 'number'` when pushing | The element type is narrower than you intended | Widen it: `(string \ | number)[]` | |||
| `Type '(string \ | number)[]' is not assignable to type 'string \ | number[]'` | Missing parentheses around the union | Write `(string \ | number)[]` or `Array<string \ | number>` |
| `Variable 'x' implicitly has type 'any[]' in some locations` | Empty literal read before it evolves | Annotate: `const x: string[] = []` | ||||
| `Property 'bark' does not exist on type 'Animal'` | The array was widened to the base type | Narrow each element, or keep the specific array type | ||||
| `any[]` flowing through your code | Source returns `any`, such as `JSON.parse` | Annotate the result and validate it at the boundary |
Choosing a spelling
Use T[] when the element is a name, such as User[] or number[]. Use Array<T> when the element is a union, a function type or an object type written inline. Both are the same to the compiler, so the choice is only about how readable the line is. Whatever you pick, apply it across the project.
Exercise
What is the difference between the types string | number[] and (string | number)[], and which of these assignments compiles: const x: string | number[] = ["a", 1]; or const y: (string | number)[] = ["a", 1];?
Show answer
string | number[] is a union of a single string and an array of numbers. (string | number)[] is one array type whose elements may each be a string or a number. The first assignment fails, because ["a", 1] is neither a string nor a number[]. The second compiles. Array<string | number> is another way to write the second type.
Exercise
Fix this code so that it compiles, and write the type of fns without using the [] shorthand: const fns: () => number[] = [() => 1, () => 2];
Show answer
The annotation describes one function that returns a number array, not an array of functions. Change it to const fns: (() => number)[] = [() => 1, () => 2];. Without the shorthand, the type is Array<() => number>.