Type Aliases: Custom Nicknames

Type Aliases: Custom Nicknames in TypeScript: The stores counter at a bus depot keeps a parts book.

The Analogy: The Parts Book at the Bus Depot

The stores counter at a bus depot keeps a parts book. Every entry carries a full description that nobody wants to write twice -- "brake shoe, rear, 406 mm by 178 mm, riveted, asbestos-free, Olympian chassis" -- so the book gives that description a short depot code, BS-406, and from then on every requisition, every stocktake and every shelf label uses the code. The code is faster to write, harder to mistype, and when the specification changes you edit the one entry in the book instead of hunting down the twenty places the description was copied into.

What the code is not is a part. It is a name for a description. Hand the storeman an actual shoe and nothing is stamped on it that says BS-406; he decides what it is by measuring it against the book. Two codes can expand to the same description -- BS-406 and the pre-merger code 44/406 both mean that shoe -- and once the book has been read out, the two requisitions are the same request. Having two names for one description does not make the depot hold two kinds of shoe.

An entry can also name a choice rather than a thing: WHEEL-NUT-STD means the 22 mm nut or the 24 mm nut, either will do. A drawing cannot say that, because a drawing shows one object, but a book entry is words, and words can offer alternatives. The same freedom lets one entry name two measurements that must be given in a fixed order, bay then shelf, and another name a job rather than an object, so that FIT-SHOE-REAR is a nickname for a procedure.

The failure mode is the one every stores clerk has seen. Someone adds a code, SHOE-FRONT, whose description is word for word the line already filed under SHOE-REAR, because at the time both axles took the same shoe. Two years later the front axle changes and only one of the two entries is updated. The requisitions still say SHOE-FRONT, the book still expands both codes to the same line, and the counter keeps issuing rear shoes to front axles. They bolt on. They pass the visual check. They are wrong, and no amount of paperwork discipline will catch it, because the two codes were never two things: they were one description wearing two names.


Syntax or Core Structure

A type alias is the keyword type, a name, an =, and any type expression at all. There is no new type at the end of it. The name is a nickname for whatever stands to the right, and the compiler substitutes one for the other freely, in both directions, wherever either appears.

// src/parts.ts
type PartCode = string;                      // a nickname for a primitive
type Axle = "front" | "rear";                // a nickname for a choice
type Slot = [bay: number, shelf: number];    // a nickname for an ordered pair
type Fitter = (s: Shoe) => string;           // a nickname for a signature

type Shoe = {                                // a nickname for a shape
    code: PartCode;
    axle: Axle;
    widthMm: number;
    lengthMm: number;
};

type Bin<T> = { slot: Slot; items: readonly T[] };   // a nickname with a hole in it

const shoe: Shoe = { code: "BS-406", axle: "rear", widthMm: 178, lengthMm: 406 };
const describe: Fitter = (s) => s.code + " " + s.axle + " " + String(s.lengthMm * s.widthMm);
const bin: Bin<Shoe> = { slot: [3, 12], items: [shoe, { ...shoe, code: "BS-407" }] };

console.log(describe(shoe));
console.log(bin.slot[0], bin.slot[1], bin.items.length);
console.log(bin.items.map((s) => s.code).join("/"));

Output:

BS-406 rear 72268
3 12 2
BS-406/BS-407

Notice that Fitter mentions Shoe two lines before Shoe is declared. Order does not matter: an alias may cite a name defined further down the file, exactly as a parts book entry may cite a code printed on a later page. Bin<T> shows the other half of the syntax, because an alias may take parameters, which makes it a nickname with a slot left blank rather than a fixed phrase.

Everything after the = is a type expression, so anything you can write in a type position can be given a name: a primitive, a union of literals, a tuple with named slots, a function signature, an object shape, a generic form built from any of those. That breadth is the whole reason type exists alongside interface, which can only ever name an object shape.


Technical Depth: A Nickname, Not a New Type

An alias introduces no identity of its own. The checker resolves the name to its expansion and then compares expansions, which is why two aliases of one type are interchangeable and why an alias can never be re-opened, augmented or tested for at runtime.

The nickname is gone before the checking starts

Give number two different domain names and you have not created two types. You have created two spellings of one type, and every assignment between them is accepted in both directions.

// src/transparent.ts
type UserId = number;
type OrderId = number;

const uid: UserId = 4471;
const oid: OrderId = uid;            // accepted: both names mean number
const plain: number = oid;           // accepted: and so does this one

type Pair = [number, number];
const p: Pair = [3, 12];
const q: [number, number] = p;       // accepted: the alias added nothing

console.log(uid, oid, plain, q[0] + q[1]);

Output:

4471 4471 4471 15

This is the SHOE-FRONT failure with the labels changed. Nothing in const total: OrderId = someUserId looks wrong, nothing reports it, and the mistake surfaces later as a lookup that finds no row. The alias documented an intention that the compiler was never asked to enforce.

Branding: a nickname that refuses to be swapped

If two identifiers must never be interchanged, the alias has to name a type that genuinely differs. The standard trick is to intersect the primitive with an object type carrying one impossible member, so the two expansions stop matching. That member is a phantom: no value ever has it.

// src/brand.ts
type UserId = number & { readonly kind: "user" };
type OrderId = number & { readonly kind: "order" };

const toUserId = (n: number): UserId => n as UserId;
const toOrderId = (n: number): OrderId => n as OrderId;

const user = toUserId(4471);
const order = toOrderId(88);

// const swapped: OrderId = user;    // refused: the two kinds differ

console.log(user + order, typeof user, JSON.stringify(user));

Output:

4559 number 4471

Output (tsc, for the commented line, first two lines):

error TS2322: Type 'UserId' is not assignable to type 'OrderId'.
  Type 'UserId' is not assignable to type '{ readonly kind: "order"; }'.

Arithmetic still works, because number & { ... } is assignable to number, and the runtime sees a plain 4471 with no kind anywhere on it. The cost is the converter: toUserId is an assertion, so the guarantee is only as strong as your discipline in routing every raw number through one of these functions. A brand catches accidental swaps between two well-formed values. It cannot catch a number that was wrong before it was branded.

What a nickname can hold that an interface cannot

Both keywords can name an object shape, and for that one job the choice is mostly taste. Everything else on this list is only available to type, except the last row, which runs the other way.

Type you need to nameWith typeWith interface
An object shapeYesYes
A closed set of string literalsYesNo, an interface names one shape
A choice between two object shapesYesNo
A primitive, or a primitive with a brand on itYesNo
A tuple with a fixed number of slotsYesNo
A bare function or constructor signatureYes, the arrow form directlyOnly as a call signature inside braces
A mapped, conditional or template literal formYesNo
Re-opening the name later to add membersNo, a second declaration is an errorYes, the declarations merge

The last row is the one that decides real arguments. An interface can be declared twice and the members pool together, which is how you add a property to Window or extend a library's types from outside; a type declared twice is a duplicate identifier and stops the build. If a shape is part of a public surface that other people may need to augment, that alone is a reason to make it an interface.

One difference that is often quoted does not hold up: which name the compiler prints back at you. For a plain object alias it usually keeps the nickname, for an intersection it often prints the members instead, and the exact choice varies with the type and the compiler version. Write code that reads well when either form appears in a message, and do not build tooling that greps for one of them.

Recursion is allowed through a shape, never through itself

An alias may mention itself, as long as the mention sits inside an array, tuple or object type. That indirection is what lets the recursion bottom out. A direct self-reference has no base case and is refused at the declaration.

// src/json.ts
type Scalar = string | number | boolean | null;
type Json = Scalar | Json[] | { [key: string]: Json };
type Tally = [nodes: number, leaves: number];

// type Bad = Bad | string;      // refused: it never bottoms out

const doc: Json = {
    depot: "Fallowfield",
    bays: [3, 12, 7],
    shoes: [{ code: "BS-406", fitted: true }, { code: "BS-407", fitted: false }],
    notes: null
};

function count(value: Json): Tally {
    if (value === null || typeof value !== "object") { return [1, 1]; }
    const children: readonly Json[] = Array.isArray(value) ? value : Object.values(value);
    let nodes = 1;
    let leaves = 0;
    for (const child of children) {
        const [n, l] = count(child);
        nodes += n;
        leaves += l;
    }
    return [nodes, leaves];
}

const [nodes, leaves] = count(doc);
console.log(nodes, leaves);
console.log(nodes - leaves, Array.isArray(doc), typeof doc);

Output:

14 9
5 false object

Output (tsc, for the commented line):

error TS2456: Type alias 'Bad' circularly references itself.

Fourteen nodes, nine of them leaves, so five containers: the document, the two arrays and the two shoe objects. The walk never asks what type anything is according to Json, because it cannot. Json describes the document to the checker; at runtime the code has to ask JavaScript directly, with typeof and Array.isArray, and null has to be handled before typeof because typeof null is "object".

The expectations that do not survive contact

Most trouble with aliases comes from expecting a nickname to behave like a new thing. These are the seven assumptions worth unlearning early.

What you might expectWhat TypeScript actually does
Two aliases of number are two typesBoth expand to number, so either is accepted where the other is wanted
An alias creates a wrapper at runtimeNothing is emitted at all; the alias exists only inside the checker
A second type of the same name adds membersIt is a duplicate identifier, TS2300, and the build stops
A class can implements an alias of a unionRefused with TS2422: only object types can be implemented
An alias may reference itself directlyRefused with TS2456; the reference must sit inside an array, tuple or object
readonly on a branded member protects somethingThe member never exists on a value, so there is nothing to protect
An alias of a shape rejects extra membersOnly for a fresh object literal, which gets the excess property check

Two of those rows are worth restating together, because they are the same fact seen twice: the alias is not present when the program runs, and it is not present as an identity when the checker compares types either. It is a substitution, performed early, and everything else follows from that.

What reaches the runtime

Compile a file that contains nothing but type declarations and the emitted JavaScript is empty. There is no constructor to call, no instanceof PartCode, no way to ask a value at runtime whether it is a Slot. Every check you want on the far side of a network boundary has to be written out by hand, in ordinary JavaScript, against the shape you hope arrived.

That makes JSON.parse(text) as Json a statement of intent rather than a verification. The assertion silences the checker and changes nothing about the bytes. If the payload is a number where the alias promised an object, the program will find out at the first property access, several stack frames from the place that lied.


Real World Example: The Issue Sheet at the Stores Counter

The counter processes a queue of requisitions against the parts book and prints one sheet at the end of the shift. Every name in the model is an alias, and each one is doing a different job: a primitive under a domain name, a closed set of words, an ordered pair, a choice between three request shapes, and a dictionary of counts.

// src/depot.ts
type PartCode = string;
type Axle = "front" | "rear";
type Slot = [bay: number, shelf: number];
type Verdict = "issued" | "short" | "returned" | "unknown" | "audited";

type Part = { code: PartCode; axle: Axle; slot: Slot; onHand: number };

type Request =
    | { kind: "issue"; code: PartCode; qty: number }
    | { kind: "return"; code: PartCode; qty: number }
    | { kind: "audit"; axle: Axle };

type Line = {
    ref: string;
    code: PartCode;
    slot: Slot | null;
    moved: number;
    left: number;
    verdict: Verdict;
};

type Stock = Record<PartCode, number>;

const BOOK: readonly Part[] = [
    { code: "BS-406", axle: "rear", slot: [3, 12], onHand: 6 },
    { code: "BS-407", axle: "front", slot: [3, 13], onHand: 2 },
    { code: "WC-118", axle: "front", slot: [1, 4], onHand: 9 },
    { code: "DR-220", axle: "rear", slot: [7, 2], onHand: 0 }
];

const QUEUE: readonly Request[] = [
    { kind: "issue", code: "BS-406", qty: 4 },
    { kind: "issue", code: "BS-407", qty: 3 },
    { kind: "return", code: "BS-406", qty: 1 },
    { kind: "issue", code: "DR-220", qty: 1 },
    { kind: "audit", axle: "front" },
    { kind: "issue", code: "XX-999", qty: 1 }
];

const ORDER: readonly Verdict[] = ["issued", "short", "returned", "unknown", "audited"];

function pad(text: string, width: number): string {
    return text.length >= width ? text : text + " ".repeat(width - text.length);
}

function signed(value: number): string {
    return value < 0 ? String(value) : "+" + String(value);
}

function where(slot: Slot | null): string {
    return slot === null ? "n/a" : String(slot[0]) + "/" + String(slot[1]);
}

function apply(stock: Stock, req: Request, ref: string): Line {
    if (req.kind === "audit") {
        const picked = BOOK.filter((p) => p.axle === req.axle);
        const total = picked.reduce((sum, p) => sum + (stock[p.code] ?? 0), 0);
        return { ref, code: req.axle, slot: null, moved: 0, left: total, verdict: "audited" };
    }
    const part = BOOK.find((p) => p.code === req.code);
    if (part === undefined) {
        return { ref, code: req.code, slot: null, moved: 0, left: 0, verdict: "unknown" };
    }
    const held = stock[part.code] ?? 0;
    if (req.kind === "return") {
        stock[part.code] = held + req.qty;
        return { ref, code: part.code, slot: part.slot, moved: req.qty, left: held + req.qty,
            verdict: "returned" };
    }
    if (held < req.qty) {
        return { ref, code: part.code, slot: part.slot, moved: 0, left: held, verdict: "short" };
    }
    stock[part.code] = held - req.qty;
    return { ref, code: part.code, slot: part.slot, moved: -req.qty, left: held - req.qty,
        verdict: "issued" };
}

function sheet(book: readonly Part[], queue: readonly Request[]): string {
    const stock: Stock = {};
    for (const p of book) { stock[p.code] = p.onHand; }
    const opening = book.reduce((sum, p) => sum + p.onHand, 0);
    const axles = new Set(book.map((p) => p.axle)).size;

    const lines: Line[] = [];
    queue.forEach((req, i) => { lines.push(apply(stock, req, "R" + String(i + 1))); });

    const out: string[] = [];
    out.push("book: " + String(book.length) + " parts on " + String(axles) + " axles");
    out.push(pad("REF", 5) + pad("CODE", 9) + pad("SLOT", 7) + pad("MOVED", 7)
        + pad("LEFT", 6) + "VERDICT");
    for (const line of lines) {
        out.push(pad(line.ref, 5) + pad(line.code, 9) + pad(where(line.slot), 7)
            + pad(signed(line.moved), 7) + pad(String(line.left), 6) + line.verdict);
    }
    const net = lines.reduce((sum, l) => sum + l.moved, 0);
    const closing = book.reduce((sum, p) => sum + (stock[p.code] ?? 0), 0);
    const tally = ORDER
        .map((v) => [v, lines.filter((l) => l.verdict === v).length] as const)
        .filter(([, n]) => n > 0)
        .map(([v, n]) => v + " x" + String(n));
    out.push("opening total: " + String(opening));
    out.push("net movement: " + signed(net));
    out.push("closing total: " + String(closing));
    out.push("verdicts: " + tally.join(", "));
    return out.join("\n");
}

console.log(sheet(BOOK, QUEUE));

Output:

book: 4 parts on 2 axles
REF  CODE     SLOT   MOVED  LEFT  VERDICT
R1   BS-406   3/12   -4     2     issued
R2   BS-407   3/13   +0     2     short
R3   BS-406   3/12   +1     3     returned
R4   DR-220   7/2    +0     0     short
R5   front    n/a    +0     11    audited
R6   XX-999   n/a    +0     0     unknown
opening total: 17
net movement: -3
closing total: 14
verdicts: issued x1, short x2, returned x1, unknown x1, audited x1

Read the sheet from the top. R1 draws four of the six rear shoes and leaves two. R2 asks for three of a part that has two, so nothing moves and the line is marked short. R3 puts one shoe back, taking that shelf to three. R4 wants a part the depot has none of. R5 is not a movement at all: it totals the front axle at the moment it runs, two of BS-407 plus nine of WC-118, and reports eleven. R6 names a code the book does not carry. The opening total of seventeen and the net movement of minus three account exactly for the closing total of fourteen, and that identity is the only cross-check the sheet offers.

The aliases are carrying their weight in three specific places. Request is a choice between three object shapes, which no interface can name, and testing req.kind is what makes req.qty reachable in two branches and req.axle in the third. Verdict is a closed set, so ORDER cannot list a verdict that does not exist and a misspelled verdict is caught where it is written rather than where it is counted. Slot | null composes the tuple alias with the absent case once, which leaves where as the only function that decides how a missing shelf prints.

The transparency shows too. PartCode is a nickname for string, so Stock is exactly Record<string, number>, and stock["anything at all"] typechecks happily. Because noUncheckedIndexedAccess is on, every read out of that dictionary arrives as a number or undefined, which is why ?? 0 appears three times in code that never actually has a missing key. The alias documents the intent of the key; it does not narrow it.

The program has real defects, and they are instructive. apply accepts stock as a parameter but reaches for the module-level BOOK directly, so the book argument to sheet only feeds the header line and the two totals: call sheet with a different book and the rows will come from the wrong one, silently. The audit line stores req.axle in a field typed PartCode, and since that is just string, "front" sits in the CODE column beside real part codes with nothing objecting; a branded PartCode would have refused it outright. Line also permits combinations that cannot happen: nothing in the type stops a short line carrying a moved count of minus four, so that invariant exists only inside apply. And left means one thing on the five part rows and something else entirely on the audit row, which is why the closing total is recomputed from stock instead of summing the column that appears to hold it.


Common Mistakes

  1. Assuming type cannot be extended: it can. type Admin = User & { level: number } is the alias equivalent of extends, and type admits unions, intersections, mapped forms and conditionals that an interface cannot express at all.
  2. Reading & as "either": string & number is not "string or number"; it is never, because nothing can be both a string and a number at once. An intersection requires every member of every operand.
  3. Believing an alias creates a distinct type: type Metres = number and type Seconds = number expand to the same primitive and are freely interchangeable. Brand the alias if that interchangeability is dangerous.
  4. Using an alias where declaration merging was needed: augmenting Window, Express.Request or any other third-party type requires interface, because a type of the same name is a duplicate-identifier error, not a merge.
  5. Aliasing once-used shapes: type MaybeString = string | undefined used in one annotation is a nickname nobody else will look up, and it forces the next reader to jump to the definition for no benefit.
  6. Treating as T on JSON.parse as a validation: the assertion silences the checker; it does not inspect the bytes. A wrong payload proceeds unchecked until a property access throws.
  7. Writing a recursive alias without a base indirection: type Bad = Bad | string is a circular reference (TS2456). The self-mention must sit inside an object, array or tuple so the recursion has a place to bottom out.
  8. Assuming a branded alias carries a runtime tag: the brand member is a phantom. typeof x still says "number", and JSON.stringify ignores it, so no serialised form remembers the brand.
  9. Expecting the compiler to print the alias name in every error: for intersections and mapped forms the checker often expands the alias into its members, and the wording changes across compiler versions, so do not build tooling that greps for one particular spelling.

Best Practices

  • Use type for unions, tuples, function signatures and anything computed; use interface for object shapes that classes implement or that other packages may need to augment. The two keywords overlap on objects; the rest of the type space belongs to type alone.
  • Be consistent within a codebase: mixing both for the same kind of shape makes reviews noisy and diffs harder to read; pick one convention and enforce it with a lint rule.
  • Name an alias after the domain concept it represents: OrderStatus, Fitter, Slot, not StringOrNumber or ObjectWithId.
  • Collect related aliases into a single types.ts per feature: one file means one import path, one place to check for existing names, and one diff when the domain changes.
  • Brand a primitive alias whenever two values of that primitive must not be swapped: the cost is one converter function per brand, and the benefit is a compile-time refusal rather than a runtime data-corruption bug.
  • Keep discriminated-union branches in a union, not behind optional fields on one shape: a union of { kind: "issue"; qty: number } and { kind: "audit"; axle: Axle } makes impossible states unrepresentable, which optional fields cannot do.
  • Validate at the boundary before asserting: when data enters from a network, a file or a user, check its shape with runtime code and narrow to the alias, rather than casting with as and hoping.
  • Document the expansion, not the keyword, when the alias is generic or recursive: a one-line comment above type Json = Scalar | Json[] | { [k: string]: Json } explaining the three arms saves more time than labelling it "a recursive type".

Practice Exercises

  1. The Parts Book: Define PartCode as a branded string, write toPartCode and toAxle converters, then prove that const x: PartCode = "BS-406" is refused while const x: PartCode = toPartCode("BS-406") is accepted.
  2. The Recursive Manifest: Write type FsNode = File | Directory where Directory has children: readonly FsNode[], build a two-level tree, and write a function that returns the total file count.
  3. The Transparent Swap: Declare type Metres = number and type Seconds = number, assign a metres value to a seconds variable, confirm the compiler is silent, then brand both and confirm it refuses.
  4. The Sheet Tally: Using the depot.ts program above, add a seventh request { kind: "audit", axle: "rear" }, hand-trace the new output line, predict the new closing total, and verify your prediction matches.