Data Structures#

TypeScript inherits JavaScript’s runtime types and adds typed structures on top.

Arrays#

const xs: number[] = [1, 2, 3];
const ys: Array<string> = ["a", "b"];

xs.push(4);
const head = xs[0];
const sub  = xs.slice(1, 3);

Tuples#

Fixed-length arrays with per-position types.

const pair: [string, number] = ["age", 36];
const [label, value] = pair;

Records#

Object literals with typed fields.

interface Point {
    x: number;
    y: number;
}

const p: Point = { x: 1, y: 2 };

type Counts = Record<string, number>;
const tally: Counts = { a: 1, b: 2 };

Maps & Sets#

ES2015 Map and Set work with full type information.

const counts = new Map<string, number>();
counts.set("a", 1);

const seen = new Set<number>([1, 2, 3]);

Enums#

enum Color { Red, Green, Blue }

const favorite: Color = Color.Green;

For lighter weight, prefer string-literal unions.

type Color = "red" | "green" | "blue";

Discriminated Unions#

A union of object types with a shared tag field is the idiomatic way to model variants.

type Shape =
    | { kind: "circle"; radius: number }
    | { kind: "square"; side: number };

function area(s: Shape): number {
    switch (s.kind) {
        case "circle": return Math.PI * s.radius ** 2;
        case "square": return s.side ** 2;
    }
}