Typescript
November 14, 2026 2 min read

Array in typescript

HS
HEMANT SINGH
Technical Writer & Educator

What is an Array?


An array is a data structure that stores multiple values in a single variable.


let students: string[] = [
"Aman",
"Rahul",
"Priya"
];

Important characteristics:

  1. An array stores multiple elements.
  2. Elements are accessed using indexes.
  3. JavaScript arrays are dynamic in size.
  4. TypeScript can enforce the type of each element.
  5. Arrays are zero-indexed.
  6. Arrays are objects in JavaScript.


Creating Arrays in TypeScript


1. Array Literal Syntax []

This is the most common and recommended way to create an array.

let numbers: number[] = [10, 20, 30, 40];

let names: string[] = ["Aman", "Rahul", "Priya"];

let isActive: boolean[] = [true, false, true];

You can also create an empty array:

let students: string[] = [];

The important difference is when you pass a single number:

let arr1 = new Array(5);
let arr2 = Array.of(5);

console.log(arr1); // Empty array with length 5
console.log(arr2); // [5]

Array Type Annotation in TypeScript


Basic Syntax

let arrayName: dataType[] = [values];

Object array

let students: { id: number; name: string }[] = [
{ id: 1, name: "Aman" },
{ id: 2, name: "Rahul" }
];

Union Types in Array Annotation

What if you want an array that accepts both numbers and strings?

Use a union type.

let data: (string | number)[] = [
"Aman",
100,
"Rahul",
200
];

Multidimensional Array Annotation

An array can contain other arrays.

For example, a matrix:

let matrix: number[][] = [
[10, 20],
[30, 40],
[50, 60]
];

7. Readonly Array Annotation

If you don't want an array to be modified, use readonly.

let subjects: readonly string[] = [
"English",
"Math",
"Science"
];

subjects.push("Hindi"); // Error
subjects[0] = "Computer"; // Error



Type Inference with as const

Now let's understand something different.

const numbers = [10, 20, 30] as const;

The inferred type becomes:

readonly [10, 20, 30]

Type Inference with Empty Arrays

This is one of the most important situations.

Consider:

let students = [];

What type does TypeScript infer?

It depends on the TypeScript configuration and context. In common strict configurations, this may be inferred as never[] initially.

What is never[]?

It is an array whose element type is never, meaning no value can be assigned as an element.

For example:

let students: never[] = [];

students.push("Aman"); // Error

Therefore, when creating an empty array, explicitly specify the intended type:

let students: string[] = [];

students.push("Aman"); // Allowed

This avoids inference problems.