Skip to content

TypeScript core types: interfaces, unions and tuples

Most TypeScript code describes data: an order, a line on that order, a status that can only take a few values, a lookup table of stock levels. This hub covers the type-level building blocks you use for that every day. It starts with interfaces, the named shapes of objects, then shows how to combine types with unions (A | B, “one of these”) and intersections (A & B, “all of these”), and finishes with three tools for more specific shapes: tuples for fixed positions, index signatures for keys you do not know in advance, and as const for values that should keep their literal types.

If you have not written TypeScript before, read the TypeScript basics tutorials first. Every sample on this page is a complete ES module from an invented online shop, OrdersPortal. They were compiled with TypeScript 7.0.2 using tsc --strict --target es2025 --module nodenext and run with Node.js 22. To try one, save it as sample.ts next to a package.json containing {"type": "module"}, then run npx tsc --strict sample.ts and node sample.js. Compiler errors are shown exactly as tsc prints them, without the file and line prefix.

Topic Since Use it when
Interfaces TypeScript 0.8 You name the shape of an object or a callable value.
Union types TypeScript 1.4 A value can be one of several types or literal values.
Intersection types TypeScript 1.6 A value must satisfy several object types at once.
Tuple types TypeScript 1.3 An array has a fixed number of positions with known types.
Index signatures Early releases; patterns in 4.4 An object is a dictionary whose keys are not known in advance.
Const assertions TypeScript 3.4 A literal value should keep its exact, read-only type.

Interfaces have been part of TypeScript since its first public release (0.8, October 2012). An interface names the shape of an object: its properties, whether each is optional (?) or readonly, and its methods. An interface can also describe a callable value with a call signature, and one interface can extend others to add members.

TypeScript’s type system is structural: a value satisfies an interface if it has the required members with compatible types, wherever it came from. No implements clause or constructor is needed, which is why plain object literals, JSON results and class instances can all satisfy the same interface. Interfaces exist only at compile time. The compiler erases them, so you cannot test value instanceof OrderLine at run time; you check the shape instead (see Type narrowing).

For the difference between an interface and a type alias, and when to prefer each, see Objects, interfaces and classes.

interface Money {
readonly amount: number;
readonly currency: "EUR" | "USD";
}
interface OrderLine {
sku: string;
quantity: number;
unitPrice: Money;
giftWrap?: boolean;
}
interface PricedLine extends OrderLine {
lineTotal: Money;
}
// A call signature: any function with this shape satisfies the interface.
interface PriceFormatter {
(money: Money): string;
}
const formatPrice: PriceFormatter = (m) => `${m.amount.toFixed(2)} ${m.currency}`;
function priceLine(line: OrderLine): PricedLine {
const amount = line.quantity * line.unitPrice.amount;
return { ...line, lineTotal: { amount, currency: line.unitPrice.currency } };
}
const priced = priceLine({
sku: "SKU-RED-01",
quantity: 3,
unitPrice: { amount: 4.5, currency: "EUR" },
});
console.log(priced.sku, formatPrice(priced.lineTotal), priced.giftWrap ?? false);

Output:

SKU-RED-01 13.50 EUR false

Pitfalls:

  • Excess property checks apply only to fresh object literals. Passing { sku: "SKU-RED-01", quantity: 1, unitPrice, colour: "red" } directly to priceLine fails with error TS2353: Object literal may only specify known properties, and 'colour' does not exist in type 'OrderLine'. The same object stored in a variable first is accepted, because extra properties are structurally allowed.
  • readonly is shallow and compile-time only. It stops money.amount = 0 in TypeScript, but nested objects stay mutable and nothing is frozen at run time.

Union types arrived in TypeScript 1.4. A | B means “a value of type A or of type B”. Unions of literal types, such as "pending" | "paid" | "shipped", are the idiomatic TypeScript replacement for a string enum: the compiler rejects any other string and the editor offers the valid values.

On a union you may only use members that exist on every member type. To use something specific to one type, you narrow the value first with a check the compiler understands, such as typeof, ===, in or a discriminant property. After the check, the compiler treats the value as the narrower type inside that branch. Narrowing has its own hub: Type narrowing, which also covers discriminated unions and exhaustiveness checks.

type OrderStatus = "pending" | "paid" | "shipped" | "cancelled";
type OrderRef = number | string; // 1042 or "ORD-1042"
function normalizeRef(ref: OrderRef): string {
// ref.toUpperCase() here would fail: number has no toUpperCase.
if (typeof ref === "number") {
return `ORD-${ref}`;
}
return ref.toUpperCase();
}
function canCancel(status: OrderStatus): boolean {
return status === "pending" || status === "paid";
}
console.log(normalizeRef(1042), normalizeRef("ord-77"));
const statuses: OrderStatus[] = ["pending", "paid", "shipped", "cancelled"];
console.log(statuses.map((s) => `${s}:${canCancel(s)}`).join(" "));

Output:

ORD-1042 ORD-77
pending:true paid:true shipped:false cancelled:false

Calling canCancel("refunded") fails at compile time:

error TS2345: Argument of type '"refunded"' is not assignable to parameter of type 'OrderStatus'.

Pitfalls:

  • Arrays of unions are not unions of arrays. (string | number)[] allows mixing in one array; string[] | number[] does not.
  • Widening loses literals. let status = "paid" is inferred as string, not "paid". Annotate it, use const, or use a const assertion.

Intersection types arrived in TypeScript 1.6. A & B describes a value that has all the members of A and of B. For object types this works like merging the two shapes, which makes intersections the usual way to add a cross-cutting concern, such as audit fields, to many types without a class hierarchy. A generic helper can return T & Extra so the caller keeps every property of its original type.

Interfaces can express much of the same with extends, and the two differ in one practical way. interface B extends A checks the members when you declare B and reports a conflict there. An intersection never reports a conflict: if both sides declare the same property with incompatible types, that property becomes never, and since TypeScript 3.9 an intersection of objects whose literal discriminants conflict reduces to never as a whole. You find out only when you try to create a value.

interface OrderCore {
id: string;
total: number;
}
interface Audited {
createdBy: string;
createdAt: string;
}
type AuditedOrder = OrderCore & Audited;
function withAudit<T extends object>(value: T, user: string): T & Audited {
return { ...value, createdBy: user, createdAt: "2026-11-18T09:30:00Z" };
}
const order: AuditedOrder = withAudit({ id: "ORD-1042", total: 59.9 }, "ada@example.test");
console.log(`${order.id} total=${order.total} by ${order.createdBy}`);
console.log(Object.keys(order).join(","));

Output:

ORD-1042 total=59.9 by ada@example.test
id,total,createdBy,createdAt

Pitfalls:

  • Conflicts become never silently. type Broken = { status: "paid" } & { status: "pending" } is never, so const b: Broken = { status: "paid" } fails with error TS2322: Type 'string' is not assignable to type 'never'., far from the real mistake.
  • string & number is never. Intersecting primitives rarely makes sense; you almost always meant a union.

Tuple types arrived in TypeScript 1.3. A tuple is an array type with a fixed sequence of positions, each with its own type: [string, number] is exactly a string followed by a number. Tuples suit small, positional results, such as a parsed CSV row or a [value, error] pair, and they destructure naturally.

Later releases made tuples more expressive. TypeScript 3.0 added optional elements ([string, number?]) and rest elements ([string, ...number[]]), and TypeScript 4.0 added labeled elements ([sku: string, quantity: number]) and variadic tuples, which let generic code spread one tuple type into another. Labels only document the positions for readers and editors; they do not change the type. Mark a tuple readonly when callers should not change it, which also removes push and other mutating methods from its type.

An array literal is inferred as an array, not a tuple: ["SKU-1", 2] is (string | number)[]. Annotate the return type or use as const to get a tuple.

type ParsedRow = readonly [sku: string, quantity: number, note?: string];
function parseRow(csvLine: string): ParsedRow {
const [sku, qty, note] = csvLine.split(",");
const quantity = Number(qty);
return note ? [sku.trim(), quantity, note.trim()] : [sku.trim(), quantity];
}
// A rest element: a customer ID followed by any number of SKUs.
type Reorder = [customerId: string, ...skus: string[]];
const rows = ["SKU-RED-01,3", "SKU-BLU-02, 1, gift"].map(parseRow);
for (const [sku, quantity, note] of rows) {
console.log(sku, quantity, note ?? "-");
}
const reorder: Reorder = ["C-77", "SKU-RED-01", "SKU-BLU-02"];
const [customerId, ...skus] = reorder;
console.log(customerId, skus.length);

Output:

SKU-RED-01 3 -
SKU-BLU-02 1 gift
C-77 2

Pitfalls:

  • Mutable tuples still allow push. const pair: [string, number] = ["SKU-1", 2]; pair.push(3); compiles and the array grows to three items at run time. Use readonly tuples for values you pass around.
  • Positional data does not scale. Past three or so positions, an object with named properties is easier to read and to change.

Index signatures have been part of TypeScript since its early releases; TypeScript 4.4 added symbol keys and template string patterns such as [key: `SKU-${string}`]: number. An index signature describes an object used as a dictionary: { [sku: string]: number } says “any string key maps to a number”. The built-in Record<string, number> is equivalent and often reads better (see Utility types).

Every explicitly declared property must be compatible with the index signature, so { [key: string]: number; label: string } is an error. By default, reading a key returns the value type even when the key is missing, so stock["SKU-NOPE"] has type number but is undefined at run time. The noUncheckedIndexedAccess option (TypeScript 4.1, not part of strict) adds | undefined to every such read and forces you to handle the missing case. When keys are truly dynamic and you add and remove them, a Map is often the better runtime structure.

type StockLevels = { [sku: `SKU-${string}`]: number };
const stock: StockLevels = {
"SKU-RED-01": 12,
"SKU-BLU-02": 0,
};
stock["SKU-GRN-03"] = 5;
function available(levels: StockLevels, sku: `SKU-${string}`): number {
const count = levels[sku]; // number by default; number | undefined with noUncheckedIndexedAccess
return count ?? 0;
}
console.log(available(stock, "SKU-RED-01"), available(stock, "SKU-NOPE-99"));
console.log(Object.entries(stock).filter(([, n]) => n > 0).map(([sku]) => sku).join(","));

Output:

12 0
SKU-RED-01,SKU-GRN-03

Writing stock["RED-01"] = 1 fails because the key does not match the pattern: error TS7053: Element implicitly has an 'any' type because expression of type '"RED-01"' can't be used to index type 'StockLevels'.

Pitfalls:

  • Missing keys look present. Without noUncheckedIndexedAccess, the compiler assumes every key exists. Turn the option on for code that does many lookups, or use Map.get, whose result already includes undefined.
  • Index signatures are wide. Prefer a union of known keys with Record<"EUR" | "USD", number> when the set of keys is fixed; you get completeness checks for free.

Const assertions arrived in TypeScript 3.4. Writing as const after a literal tells the compiler to infer the narrowest type it can: string and number literals keep their literal types, arrays become readonly tuples and object properties become readonly. The main use is to define a list or configuration object once, as data, and derive types from it, so the values and the type can never drift apart.

typeof STATUSES[number] turns a readonly ["pending", "paid"] tuple into the union "pending" | "paid". Combine as const with satisfies (TypeScript 4.9) to check a configuration object against a wider type while keeping its literal types; see Type assertions. Despite its name, a const assertion is not a runtime assertion and does not freeze anything; call Object.freeze if you need run-time immutability.

const ORDER_STATUSES = ["pending", "paid", "shipped", "cancelled"] as const;
type OrderStatus = (typeof ORDER_STATUSES)[number];
const SHIPPING = {
standard: { label: "Standard", days: 5, fee: 4.99 },
express: { label: "Express", days: 1, fee: 12.5 },
} as const satisfies Record<string, { label: string; days: number; fee: number }>;
type ShippingMethod = keyof typeof SHIPPING;
function isOrderStatus(value: string): value is OrderStatus {
return (ORDER_STATUSES as readonly string[]).includes(value);
}
function quote(method: ShippingMethod): string {
const option = SHIPPING[method];
return `${option.label}: ${option.fee} EUR, ${option.days} day(s)`;
}
console.log(isOrderStatus("paid"), isOrderStatus("refunded"));
console.log(quote("express"));

Output:

true false
Express: 12.5 EUR, 1 day(s)

Pitfalls:

  • Read-only results do not fit mutable parameters. Passing ORDER_STATUSES to a function that takes string[] fails with error TS4104: The type 'readonly ["pending", "paid", "shipped", "cancelled"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'. Declare such parameters as readonly string[].
  • .includes on a literal tuple is strict. ORDER_STATUSES.includes(value) with a plain string argument fails with error TS2345: Argument of type 'string' is not assignable to parameter of type '"cancelled" | "paid" | "pending" | "shipped"'. Widen the array as in the sample, or write a type guard.
  • To name the shape of an object that other code implements or extends, use an interface.
  • To say “one of these”, including a fixed set of string values, use a union; narrow before using members specific to one case.
  • To add the same extra fields to many types, use an intersection; prefer extends when you want conflicts reported at the declaration.
  • For a short, positional result, use a tuple; past three positions, use an object.
  • For dictionaries with unknown keys, use an index signature or Record, and consider noUncheckedIndexedAccess or a Map.
  • To derive types from a list or configuration object you already have, use as const, with satisfies to check its shape.

What does structural typing mean in TypeScript, and what is one consequence? A value is compatible with a type if it has the required members with compatible types, regardless of its declared name or how it was created. One consequence is that two unrelated interfaces with the same members are interchangeable, and a class instance satisfies an interface it never mentions. Another is that types cannot be checked at run time with instanceof unless they are classes.

What is the difference between A | B and A & B for two object types? A value of A | B has the members of A or of B, so without narrowing you can only use members common to both. A value of A & B has the members of both, so you can use all of them. For primitives, string & number is never.

Why does const pair: [string, number] = ["SKU-1", 2]; pair.push(3); compile? Mutable tuple types are still arrays, and push accepts any element type of the tuple, here string | number. Declare the tuple readonly [string, number] to remove mutating methods from its type.

What does as const change about ["pending", "paid"]? Without it, the type is string[]. With it, the type is readonly ["pending", "paid"]: a read-only tuple of literal types, from which (typeof x)[number] derives the union "pending" | "paid". Nothing changes at run time.

Why is stock["SKU-MISSING"] typed as number with an index signature, and how do you fix that? By default TypeScript assumes every key in an index signature exists. Turning on noUncheckedIndexedAccess makes such reads number | undefined, so the compiler forces a check. Alternatively use a Map, whose get already returns V | undefined.

Senior scenario: OrdersPortal’s order status strings are duplicated across the API client, the UI and the database layer, and a new status broke two screens. How would you fix this with types? Define the statuses once as data with as const in a shared module, derive the OrderStatus union from it, and use that union in the API response types, UI components and repository functions. Add a type guard built on the same array for validating data at the boundary. Then make every switch over a status exhaustive with a never check, so adding a status produces compile errors in every place that must handle it, not a broken screen in production.