Sub topic 9
Modeling Failure with a Result Union
Assume you know basic TypeScript functions, generics, union types, type narrowing, and JavaScript Promise and async/await. This chapter focuses on making expected failure visible in a function's return type.
A promise can fulfill with a value or reject with an error. TypeScript records the fulfilled value in Promise<T>, but it does not record the type of a rejection:
async function readUser(id: number): Promise<User> {
// The promise may reject, but Promise<User> does not describe why.
}A Result union represents both outcomes as data. A union type is a type that can be one of several defined shapes.
Define a discriminated Result union
Use a shared property, such as ok, to distinguish success from failure:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };T is the success value type. E is the error type, and it defaults to Error. The literal types true and false make ok a discriminant. TypeScript uses that property to narrow the union.
function show(result: Result<number>): string {
if (result.ok) {
return `Value: ${result.value}`;
}
return `Error: ${result.error.message}`;
}
console.log(show({ ok: true, value: 42 }));
console.log(show({ ok: false, error: new Error("Unavailable") }));Inside the if branch, TypeScript knows that result has a value. After the branch, it knows that result has an error.
Convert promise rejection into Result
A generic helper can preserve the resolved type of any promise:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
async function attempt<T>(promise: Promise<T>): Promise<Result<T>> {
try {
return { ok: true, value: await promise };
} catch (error: unknown) {
const normalized =
error instanceof Error ? error : new Error(String(error));
return { ok: false, error: normalized };
}
}
async function loadName(): Promise<string> {
return "Ada";
}
async function main(): Promise<void> {
const result = await attempt(loadName());
if (result.ok) {
console.log(result.value.toUpperCase());
} else {
console.error(result.error.message);
}
}
void main();The helper returns Promise<Result<T>>. If the input is Promise<string>, the result becomes Promise<Result<string>>. The generic parameter preserves the resolved value instead of replacing it with unknown or any.
The catch variable is explicitly unknown. A JavaScript promise can reject with any value, including a string or an object that is not an Error. The instanceof Error check narrows the value before its message property is read.
Choose the error type deliberately
The default Error type is useful when callers only need a message. A domain-specific error union is better when callers must respond differently to known failures.
type UserError =
| { kind: "not-found"; id: number }
| { kind: "unauthorized" }
| { kind: "network"; message: string };
type UserResult = Result<{ id: number; name: string }, UserError>;
function describeUserFailure(result: UserResult): string {
if (result.ok) {
return result.value.name;
}
switch (result.error.kind) {
case "not-found":
return `No user exists for ${result.error.id}`;
case "unauthorized":
return "Sign in to continue";
case "network":
return `Try again: ${result.error.message}`;
}
}This approach makes expected failures exhaustive. If you add another kind, TypeScript can help locate code that must handle it.
Result compared with thrown errors
Use thrown errors when a failure is exceptional, unexpected, or handled by a higher-level boundary. Use Result when failure is an expected part of normal control flow, such as validation, authorization, or a missing record.
A Result also works well when a function's caller should be forced to make a decision. The caller cannot access value without first checking ok.
Exercise
If attempt receives a Promise<number>, what is the type of the value returned by await attempt(promise)?
Show answer
Result<number>. The outer promise has been awaited, and the generic parameter preserves the number type.