Union Types
TS · Type Aliasessyntax
type Name = TypeA | TypeB | TypeC;example
type Status = "pending" | "active" | "archived";
type ApiResponse = SuccessResult | ErrorResult;
interface SuccessResult {
ok: true;
data: unknown;
}
interface ErrorResult {
ok: false;
errorCode: number;
message: string;
}
function handleResponse(res: ApiResponse) {
if (res.ok) {
console.log(res.data); // narrowed to SuccessResult
} else {
console.error(res.message); // narrowed to ErrorResult
}
}output
// Union means 'one of these types' — must narrow before accessing specific membersNote You can only access properties common to ALL members of a union without narrowing first. Use a shared discriminant property (like 'ok' above) to let TypeScript narrow automatically in conditionals.