Typed Arrays

Declare arrays where every element must be the same type.

Syntaxlet nums: number[] = [1, 2, 3];

An array type describes a list whose elements all share a type. There are two equivalent ways to write it:

  • number[] — an array of numbers.
  • Array<number> — the generic form, same meaning.

If you try to push a value of the wrong type, TypeScript reports an error.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A product list component declares its items as Product[] so TypeScript prevents accidentally mixing in non-product objects.
  • A function returns string[] from a database query so callers can safely call string methods on every element.
  • An analytics module stores number[] for page view counts, allowing typed reduce and map operations.

More examples

Declare a typed array

Shows three typed array declarations and demonstrates that push rejects an element of the wrong type.

Example · ts
const names: string[] = ['Alice', 'Bob', 'Carol'];
const scores: number[] = [98, 72, 85];
const flags: boolean[] = [true, false, true];

names.push(42); // Error: Argument of type 'number' is not assignable

Generic Array<T> syntax

Uses the generic Array<T> syntax as an alternative to T[], and defines a generic helper to retrieve the first element.

Example · ts
const ids: Array<number> = [1, 2, 3];
const tags: Array<string> = ['ts', 'web', 'types'];

function first<T>(arr: Array<T>): T | undefined {
  return arr[0];
}

Typed array from map

Declares an array of interface objects and infers the correct string[] type from a map call over it.

Example · ts
interface Product {
  id: number;
  name: string;
  price: number;
}

const products: Product[] = [
  { id: 1, name: 'Pen', price: 1.99 },
  { id: 2, name: 'Notebook', price: 4.49 },
];

const names: string[] = products.map((p) => p.name);

Discussion

  • Be the first to comment on this lesson.