typeStatus="pending"|"active"|"archived";typeApiResponse=SuccessResult|ErrorResult;interfaceSuccessResult{
ok:true;
data: unknown;}interfaceErrorResult{
ok:false;
errorCode: number;
message: string;}functionhandleResponse(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 members
Note 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.
typeResult<T,E= string>=|{ ok:true; value:T}|{ ok:false; error:E};functionparseAge(input: string):Result<number>{const num =parseInt(input,10);if(isNaN(num))return{ ok:false, error:"Not a valid number"};if(num <0|| num >150)return{ ok:false, error:"Age out of range"};return{ ok:true, value: num };}const result =parseAge("25");if(result.ok){console.log(`Age: ${result.value}`);// narrowed to { ok: true; value: number }}else{console.log(`Invalid: ${result.error}`);// narrowed to { ok: false; error: string }}
Output
// Discriminated union forces callers to handle both success and failure
Note The Result pattern replaces throwing exceptions with explicit return types. Callers cannot forget to handle the error case because TypeScript requires narrowing before accessing .value or .error. This is inspired by Rust's Result<T, E> type.
Frequently asked questions
How does TypeScript handle either type?
TypeScript covers this with 2 copy-ready snippets on this page. The "Union Types" snippet in TypeScript uses `type Name = TypeA | TypeB | TypeC;`.
Which code does the TypeScript example use?
The "Union Types" snippet uses `type Name = TypeA | TypeB | TypeC;`, from the Type Aliases section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "either type"?
Besides "Union Types", this page also shows "Result Type Pattern".
Is there anything to watch out for?
Yes. For "Union Types": 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.