Model your application's states with unions the compiler checks on your behalf.
Open this lesson in KodokonA literal type restricts a value to exact content: 'info' rather than string. It's the foundation of APIs that are impossible to misuse: the compiler rejects any value outside the list, and your editor offers autocompletion.
type Level = "info" | "warn" | "error";
function log(level: Level, message: string): void {
console.log(`[${level}] ${message}`);
}
log("info", "Server started");
// log("fatal", "Boom"); -> rejected by the compilerThe next step is combining object types that share a common literal property, called the discriminant. Each state of a network call, for example, carries only the data that belongs to it: accessing data while loading is simply impossible.
type ApiState =
| { status: "loading" }
| { status: "success"; data: string[] }
| { status: "error"; message: string };
function render(state: ApiState): string {
switch (state.status) {
case "loading":
return "Loading...";
case "success":
return state.data.join(", ");
case "error":
return state.message;
}
}In each case, TypeScript narrows the type: after case 'error', state.message exists and state.data does not. This mechanism, called narrowing, replaces fragile manual checks. Add an exhaustiveness guard to lock the whole thing down.
function assertNever(value: never): never {
throw new Error("Unhandled case: " + String(value));
}
function label(state: ApiState): string {
switch (state.status) {
case "loading": return "In progress";
case "success": return "Done";
case "error": return "Failed";
default: return assertNever(state);
}
}