Union Types Close the Door · TypeScript

Ch 2 · The Types You Will Use Every Day — card 3 of 5.

A union type uses the vertical bar to say a value may be one of several types. This is how you describe the messy realities of real data — an ID that might be a number or a string, a field that might be missing.

let invoiceId: number | string;

invoiceId = 4021;
console.log("numeric id: " + invoiceId);

invoiceId = "INV-4021";
console.log("string id: " + invoiceId);

The important half is what the union refuses. Assign a boolean to invoiceId and the compiler stops you. A union is not a loophole — it is a list of the only permitted possibilities, and TypeScript will make you handle each one before you use the value.

The block below is deliberately wrong. Run it and read the error: this is what the checker doing its job actually looks like.

let invoiceId: number | string;
invoiceId = true;
console.log(invoiceId);