Skip to main content

How do you declare an array in TypeScript?

1. A simple array of primitives

Syntax 1 - via type[]

javascript
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

javascript
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

javascript
interface User { id: number; name: string; } const users: User[] = [ { id: 1, name: "Tim" }, { id: 2, name: "Max" }, ];

Every element must match the User interface.


3. An array with several possible types (union)

javascript
const data: (string | number)[] = [1, "two", 3, "four"];

Every element must be either string or number.


4. An array of arrays (two-dimensional)

javascript
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:

javascript
const ids: readonly number[] = [1, 2, 3]; ids.push(4); // Error: push is not allowed

or the equivalent form:

javascript
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.

javascript
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[])

javascript
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:

javascript
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: string

A universal way to write type-safe functions for arrays.


9. A type for an array via type or interface

javascript
type StringArray = string[]; type Matrix = number[][]; interface UserArray { [index: number]: User; }

This lets you reuse the type in different places.


Summary

TaskSyntaxExample
Simple array of numbersnumber[][1, 2, 3]
Array of stringsstring[]["a", "b"]
AlternativeArray<number>[1, 2, 3]
Array of objectsUser[][{id:1,name:"Tim"}]
Several types(string | number)[]["a", 1]
Two-dimensional arraynumber[][][[1,2],[3,4]]
Read-onlyreadonly string[]["A","B"]
Tuple[string, number]["id", 5]

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.