Sub topic 11
A Result type for fallible functions
This chapter assumes you know the basics of discriminated unions: a union of object types that share a literal-typed property, which if and switch use to narrow the type. It also assumes strict: true in your tsconfig.json. Narrowing on the discriminant and the never exhaustiveness check from earlier chapters are used here without re-explaining them.
Why functions need a way to fail visibly
A TypeScript function signature such as (input: string) => number says what the function returns when it works. It says nothing about failure. If the function throws, the compiler does not know. A caller can forget the try/catch, and the error appears at runtime, far from where the mistake was made.
A Result type puts the failure into the return type. The function returns one of two tagged variants: a success that carries a value, or a failure that carries an error. The caller cannot get at the value without first checking which variant it received.
This is the generic discriminated union from the previous chapter, used for a specific job.
Defining Result
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function ok<T>(value: T): Result<T, never> {
return { ok: true, value };
}
function err<E>(error: E): Result<never, E> {
return { ok: false, error };
}
function parsePort(input: string): Result<number, string> {
const port = Number(input);
if (input.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) {
return err(`Invalid port: ${input}`);
}
return ok(port);
}
const result = parsePort("8080");
if (result.ok) {
console.log(result.value);
} else {
console.log(result.error);
}The type has three parts:
Tis the type of the success value.Eis the type of the error.okis the discriminant. Its type is the literaltruein one member and the literalfalsein the other.
A boolean works as a discriminant because true and false are literal types. Checking result.ok narrows result to the matching member. Inside the if branch, result.value exists and result.error does not. In the else branch it is the other way around.
The helpers ok and err are optional, but they keep call sites short. Their return types use never for the unused side. Result<number, never> is assignable to Result<number, string>, because a failure variant carrying a never error can never actually occur. This is why parsePort can return both ok(port) and err(...) and still satisfy its declared return type.
Choosing the discriminant: ok or kind
Two conventions are common.
| Convention | Shape | Good for |
|---|---|---|
| Boolean tag | `{ ok: true; value: T }` / `{ ok: false; error: E }` | Exactly two outcomes, short checks like `if (result.ok)` |
| String tag | `{ kind: "success"; ... }` / `{ kind: "failure"; ... }` | Consistency with other unions in the codebase, or more than two outcomes |
Use the boolean form for a plain success-or-failure result. If a function has outcomes such as "found", "not found", and "forbidden", model those as a larger discriminated union instead of forcing them into Result.
Making the error type informative
string errors are easy to write but hard to handle. The caller can only print them. Because the error is itself a type, it can be a discriminated union. Callers can then branch on it, and the compiler checks that every error case is handled.
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function ok<T>(value: T): Result<T, never> {
return { ok: true, value };
}
function err<E>(error: E): Result<never, E> {
return { ok: false, error };
}
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
type PortError =
| { kind: "empty" }
| { kind: "not_an_integer"; input: string }
| { kind: "out_of_range"; port: number };
function parsePort(input: string): Result<number, PortError> {
if (input.trim() === "") {
return err({ kind: "empty" });
}
const port = Number(input);
if (!Number.isInteger(port)) {
return err({ kind: "not_an_integer", input });
}
if (port < 0 || port > 65535) {
return err({ kind: "out_of_range", port });
}
return ok(port);
}
function describePortError(error: PortError): string {
switch (error.kind) {
case "empty":
return "No port was given.";
case "not_an_integer":
return `"${error.input}" is not a whole number.`;
case "out_of_range":
return `${error.port} is outside 0-65535.`;
default:
return assertNever(error);
}
}
const parsed = parsePort("70000");
if (!parsed.ok) {
console.log(describePortError(parsed.error));
}Adding a fourth PortError variant now makes describePortError fail to compile until it handles the new case. The failure modes of a function become part of its documented, checked contract.
Putting a literal into err({ kind: "empty" }) works without as const here. The expected type from the return annotation Result<number, PortError> keeps "empty" as a literal. Without a contextual type, the literal would widen to string, as the pitfalls chapter explains.
Transforming results without unwrapping them
Checking ok at every step gets repetitive when several fallible steps run in sequence. Two small functions cover most needs. They assume the Result, ok, and err definitions above.
function map<T, U, E>(
result: Result<T, E>,
fn: (value: T) => U
): Result<U, E> {
return result.ok ? ok(fn(result.value)) : result;
}
function andThen<T, U, E>(
result: Result<T, E>,
fn: (value: T) => Result<U, E>
): Result<U, E> {
return result.ok ? fn(result.value) : result;
}
function parseJson(text: string): Result<unknown, string> {
try {
return ok(JSON.parse(text));
} catch (e) {
return err(e instanceof Error ? e.message : String(e));
}
}
const doubled = map(ok(21), (n) => n * 2);
console.log(doubled); // { ok: true, value: 42 }
const failed = map(err("boom") as Result<number, string>, (n) => n * 2);
console.log(failed); // { ok: false, error: "boom" }
console.log(parseJson("{ not json"));mapapplies a function to the success value and passes a failure through unchanged.andThenis for steps that can themselves fail. Its callback returns aResult, andandThenavoids a nestedResult<Result<...>>.parseJsonshows the usual way to bring throwing code into this style. Atry/catchat the edge converts exceptions into values, and the rest of the program works withResult.
Both helpers require the error type E to be the same on both sides. If two steps fail with different error types, either widen E to a union of both error types at the call site or convert one error into the other first.
Common mistakes with Result
- Testing the value instead of
ok. Writingif (result.value)is a bug. A port of0, an empty string, orfalseis a valid success value but is falsy. Always checkresult.ok. Also,result.valueon the unnarrowed union is a compile error, becausevaluedoes not exist on the failure member. - Declaring
okas a plainboolean. A type such as{ ok: boolean; value?: T; error?: E }allowsok: truewith no value andok: falsewith a value. Narrowing no longer gives you a definedvalue. Keep the two members separate with literaltrueandfalse. - Mixing throwing and returning. If
parsePortreturns aResultbut sometimes throws on unexpected input, callers get the worst of both. Decide which failures are expected and returned (bad user input, missing files) and which are bugs that should throw (violated invariants). - Widening the tag. An object built as
const r = { ok: true, value: 1 }hasok: boolean, so it is not assignable toResult<number, string>. Return the object directly from an annotated function, use theokhelper, or addas const. - Discarding the result. TypeScript does not warn when you call
parsePort(input)and ignore the return value. A linter rule such as@typescript-eslint/no-floating-promisescovers promises only, so ignored synchronous results need code review or a custom rule.
When to use Result and when to throw
| Situation | Prefer |
|---|---|
| Bad user input, parse failures, "not found" lookups | `Result` |
| Callers are expected to handle each failure differently | `Result` with a union error type |
| A programmer error or broken invariant | `throw` |
| Failure should abort the whole operation and a top-level handler exists | `throw` |
| Library code whose callers use `try`/`catch` throughout | Follow the surrounding convention |
A Result carries a small cost. Every call site has a branch, and composing steps needs helpers like andThen. That cost pays off when the failure cases matter to the caller. It is wasted when every caller would only rethrow.
Summary
Result<T, E> is a generic discriminated union with a boolean ok tag. Checking ok narrows the value to the success or failure member. Giving E a discriminated union of its own lets the compiler verify that every error case is handled. Small helpers such as map and andThen keep sequences of fallible steps readable. Keep the tag as a literal type, check ok rather than the value, and decide deliberately which failures are returned and which are thrown.
Exercise
A teammate writes const r = parsePort(input); if (r.value) { use(r.value); } and reports that port 0 is silently treated as an error. The code does not compile, either. What are the two problems, and what is the fix?
Show answer
First, value exists only on the { ok: true } member, so reading r.value on the unnarrowed union is a compile error. Second, even if it were allowed, truthiness is the wrong test, because 0 is a valid port but falsy. The fix is to check the discriminant: if (r.ok) { use(r.value); }. Narrowing on r.ok makes value available, and it treats port 0 as a success.
Exercise
Write a function parseHostPort(input: string): Result<{ host: string; port: number }, string> that splits "example.com:8080" on the last :. It must fail with a string error if there is no colon or the host is empty. Use andThen or map with the parsePort that returns Result<number, PortError> so the port step is reused. What must you change so the types line up?
Show answer
The two steps have different error types (string and PortError), and andThen needs one shared E. Convert the port error first, or widen E. For example:
function parseHostPort(input: string): Result<{ host: string; port: number }, string> {
const index = input.lastIndexOf(":");
if (index === -1) return err("Missing ':' separator");
const host = input.slice(0, index);
if (host === "") return err("Empty host");
const port = parsePort(input.slice(index + 1));
if (!port.ok) return err(describePortError(port.error));
return ok({ host, port: port.value });
}
Here the port error is turned into a string with describePortError before returning, so the declared E of string holds. Declaring the return type as Result<{ host: string; port: number }, string | PortError> would also work.
Exercise
Why does const r = { ok: true, value: 1 }; const typed: Result<number, string> = r; fail to compile, and give two ways to fix it.
Show answer
Without a contextual type, the property ok in a plain const object literal widens from true to boolean. The object then matches neither union member. Fixes: annotate the variable (const r: Result<number, string> = { ok: true, value: 1 };), or use as const (const r = { ok: true, value: 1 } as const;). Using the ok(1) helper also works.