How do you declare an array in TypeScript?
1. A simple array of primitives
Syntax 1 - via type[]
const numbers: number[] = [1, 2, 3, 4];
const names: string[] = ["Tim", "Max", "Bob"];The most common and convenient way is
type[].
Syntax 2 - via the Array<type> generic
const numbers: Array<number> = [1, 2, 3, 4];
const names: Array<string> = ["Tim", "Max", "Bob"];Fully equivalent to
number[], just a different notation (useful when the inner type is complex).
2. An array of objects
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "Tim" },
{ id: 2, name: "Max" },
];Every element must match the
Userinterface.
3. An array with several possible types (union)
const data: (string | number)[] = [1, "two", 3, "four"];Every element must be either
stringornumber.
4. An array of arrays (two-dimensional)
const matrix: number[][] = [
[1, 2],
[3, 4],
];The type reads as "an array of arrays of numbers".
5. An immutable array (readonly)
If you need to forbid modifying the array:
const ids: readonly number[] = [1, 2, 3];
ids.push(4); // Error: push is not allowedor the equivalent form:
const ids: ReadonlyArray<number> = [1, 2, 3];Useful for constant data (for example, lists of roles or statuses).
6. A fixed-length array (tuple)
A tuple is a "fixed-length array" with element types known in advance.
const pair: [string, number] = ["age", 25];
pair[0]is always a string,pair[1]is always a number.
7. An array of unknown content (any[])
const arr: any[] = [1, "text", true, { key: "value" }];Such an array disables type checking, try to avoid
any[]when you can specify an exact type.
8. An array with a generic
If a function needs to work with an array of any elements:
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const n = firstElement([1, 2, 3]); // n: number
const s = firstElement(["a", "b", "c"]); // s: stringA universal way to write type-safe functions for arrays.
9. A type for an array via type or interface
type StringArray = string[];
type Matrix = number[][];
interface UserArray {
[index: number]: User;
}This lets you reuse the type in different places.
Summary
| Task | Syntax | Example |
|---|---|---|
| Simple array of numbers | number[] | [1, 2, 3] |
| Array of strings | string[] | ["a", "b"] |
| Alternative | Array<number> | [1, 2, 3] |
| Array of objects | User[] | [{id:1,name:"Tim"}] |
| Several types | (string | number)[] | ["a", 1] |
| Two-dimensional array | number[][] | [[1,2],[3,4]] |
| Read-only | readonly string[] | ["A","B"] |
| Tuple | [string, number] | ["id", 5] |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.