Literal Types Are Cheap Validation · TypeScript
Ch 2 · The Types You Will Use Every Day — card 4 of 5.
A union does not have to be a union of types. It can be a union of exact values, and that is one of the most useful things in the whole language. An invoice status is not "a string" — it is one of four specific words. Say so, and every typo becomes a compile error instead of a broken filter in production.
type Status = "draft" | "sent" | "paid" | "overdue";
const current: Status = "sent";
function isOwed(s: Status): boolean {
return s === "sent" || s === "overdue";
}
console.log("status: " + current);
console.log("client owes money: " + isOwed(current));Now const current: Status = "Sent" fails to compile, because of one capital letter. Without literal types that same capital letter ships, the dashboard shows zero unpaid invoices, and the client finds out at the end of the month.