Sub topic 9
Modeling failure with a Result union
This chapter assumes you know basic TypeScript types and generics, async/await, and how to narrow union types. It also assumes you have read the earlier chapters on Promise<T>, async functions, and why a catch variable is unknown.
The problem: failure is invisible in a promise type
Look at this signature:
declare function getUser(id: number): Promise<{ id: number; name: string }>;The type says what a successful call produces. It says nothing about failure. The call might reject with an Error, a string, or anything else, and no caller is forced to handle it. TypeScript has no throws clause, so a function that can fail and one that cannot look the same.
A Result union moves the failure into the return type. A caller then has to look at the outcome before it can reach the value.
The Result type
A Result is a union of two object shapes that share a discriminant property. Here the discriminant is ok:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };Tis the type of the success value.Eis the type of the failure. It defaults toError.okis a boolean literal type,truein one member andfalsein the other. TypeScript uses it to tell the members apart.
Before you check ok, you can read only ok. After the check, TypeScript knows which member you hold:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function describe(r: Result<number>): string {
if (r.ok) {
return `got ${r.value.toFixed(1)}`;
}
return `failed: ${r.error.message}`;
}
console.log(describe({ ok: true, value: 3 }));
console.log(describe({ ok: false, error: new Error("nope") }));Reading r.value outside the if is a compile error, because value does not exist on the failure member. That error is the point of the pattern.
Turning a promise into a Result
The attempt helper wraps a promise and never rejects. It catches the rejection and returns it as data:
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 (e) {
return { ok: false, error: e instanceof Error ? e : new Error(String(e)) };
}
}
async function loadUser(id: number): Promise<{ id: number; name: string }> {
if (id < 0) {
throw new RangeError("id must be non-negative");
}
return { id, name: `user${id}` };
}
async function main(): Promise<void> {
const result = await attempt(loadUser(-1));
if (result.ok) {
console.log(result.value.name);
} else {
console.error(result.error.message);
}
}
void main();Three details matter here.
- The
awaitinsidetryis required. Writingreturn { ok: true, value: promise }would put an unresolved promise in thevaluefield. Writingreturn promisewould let the rejection escape thetryblock. Onlyawait promiseinside thetrycatches it. - The
catchvariable isunknown. You cannot put it directly in anErrorfield, so the helper narrows it withinstanceof. Anything that is not anErroris wrapped. - The return type is inferred through the generic. For
attempt(loadUser(-1)),Tis inferred as{ id: number; name: string }, soresult.value.nameis typed asstring.
Keeping the original thrown value
Wrapping with new Error(String(e)) loses the original value. If a library throws an object with useful fields, you want to keep it. The cause option on Error does this. It needs a lib setting of ES2022 or later:
function toError(e: unknown): Error {
if (e instanceof Error) {
return e;
}
return new Error(`Non-Error thrown: ${String(e)}`, { cause: e });
}
const wrapped = toError({ code: 42 });
console.log(wrapped.message);
console.log(wrapped.cause);Moving the normalization into one function keeps every attempt-style helper consistent.
A typed error instead of plain Error
The default E = Error tells callers little. You can give failures a specific class and let callers narrow on it:
class HttpError extends Error {
constructor(readonly status: number) {
super(`HTTP ${status}`);
this.name = "HttpError";
}
}
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
async function getText(url: string): Promise<Result<string, HttpError | TypeError>> {
try {
const res = await fetch(url);
if (!res.ok) {
return { ok: false, error: new HttpError(res.status) };
}
return { ok: true, value: await res.text() };
} catch (e) {
if (e instanceof TypeError) {
return { ok: false, error: e };
}
throw e;
}
}
async function main(): Promise<void> {
const r = await getText("https://example.com");
if (!r.ok) {
if (r.error instanceof HttpError) {
console.error("status", r.error.status);
} else {
console.error("network problem", r.error.message);
}
return;
}
console.log(r.value.length);
}
void main();The function lists the two failures it expects, and the compiler enforces that list on the return statements. It rethrows anything else, such as a bug in your own code. The signature promises only the failures you chose to model.
Working with Results
Transforming the success value
A small mapResult function applies a function to the value and passes failures through unchanged:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function mapResult<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {
return r.ok ? { ok: true, value: fn(r.value) } : r;
}
const length = mapResult({ ok: true, value: "hello" } as Result<string>, (s) => s.length);
console.log(length);In the failure branch, r has been narrowed to { ok: false; error: E }. That is assignable to Result<U, E>, so no new object is needed.
Running several operations together
A function built on attempt never rejects. That changes how Promise.all behaves:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
declare function attempt<T>(promise: Promise<T>): Promise<Result<T>>;
declare function getUser(id: number): Promise<{ id: number; name: string }>;
declare function getPosts(id: number): Promise<string[]>;
async function load(id: number): Promise<string> {
const [user, posts] = await Promise.all([
attempt(getUser(id)),
attempt(getPosts(id)),
]);
if (!user.ok) {
return `no user: ${user.error.message}`;
}
const count = posts.ok ? posts.value.length : 0;
return `${user.value.name} has ${count} posts`;
}With raw promises, the first rejection makes Promise.all reject and you lose the other result. Here both calls always finish, and you decide per result what a failure means. The tuple keeps each position's type, so user and posts have different value types.
Wrapping a function instead of a promise
attempt(promise) has a gap. If you pass the result of a non-async function that throws synchronously, the exception happens while evaluating the argument, before attempt runs:
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
async function attemptFn<T>(fn: () => Promise<T> | T): Promise<Result<T>> {
try {
return { ok: true, value: await fn() };
} catch (e) {
return { ok: false, error: e instanceof Error ? e : new Error(String(e)) };
}
}
function parseConfig(text: string): { retries: number } {
return JSON.parse(text) as { retries: number };
}
async function main(): Promise<void> {
const r = await attemptFn(() => parseConfig("{ not json"));
console.log(r.ok ? "parsed" : `bad config: ${r.error.message}`);
}
void main();Because fn is called inside the try, both synchronous throws and rejections become failures.
When to use a Result and when to throw
A Result is not better than exceptions in every case. It trades convenience for visibility.
| Situation | Better fit | Reason |
|---|---|---|
| Expected failure the caller should handle (not found, validation, HTTP 404) | Result | The type forces a decision at the call site |
| Programmer error or broken invariant | Throw | Callers cannot do anything useful, so let it propagate |
| Many calls in a row where any failure aborts the whole task | Throw | `try`/`catch` once is shorter than checking every `ok` |
| Independent operations where partial success is fine | Result | Failures stay as data, as with `Promise.allSettled` |
| Code that must interoperate with libraries expecting rejections | Throw | Mixing styles forces conversions at every boundary |
Whichever you choose, apply it consistently within a module. A codebase where some functions throw and others return Results leaves callers guessing, and the type system cannot tell them which.
Common mistakes
- Forgetting that Result checks are manual. A Result that is never inspected is a silently ignored failure. TypeScript forces you to check before using the
value, but it does not force you to use the Result at all. Ano-floating-promiseslint rule still matters forattempt(...)calls whose result is dropped. - Mixing styles in one function. A function that returns
Promise<Result<T>>but also lets some errors reject has two failure channels. Document or eliminate the second. - Over-wide
E.Result<T, unknown>forces every caller to narrow and adds little over a plain rejection. Use a union of specific error types. - Skipping normalization. Putting an
unknowncaught value in anError-typed field with a cast hides non-Errorthrows. Use a function liketoError.
Exercise
Why does attempt write value: await promise inside the try block, and what goes wrong if you write return { ok: true, value: promise } instead?
Show answer
The await inside try is what catches a rejection, because a rejected promise throws at the await. Without it, the rejection never reaches the catch. The object would also contain the promise itself, so value would have type Promise<T> instead of T, and the return type would not match Result<T>.
Exercise
A function has the signature async function find(id: number): Promise<Result<string, "not_found" | "forbidden">>. After const r = await find(1); and if (!r.ok) { ... }, what type does r.error have inside the block, and how would you handle each case exhaustively?
Show answer
Inside the block, r.error has the type "not_found" | "forbidden". Use a switch (r.error) with one case per literal. Add a default branch that assigns r.error to a variable of type never. If someone adds a third error literal later, that assignment becomes a compile error and points to the unhandled case.