Sub topic 11
A Result Type for Fallible Functions
This chapter assumes you know object types, union types, literal types, functions, and if statements. It also assumes strict: true is enabled in your tsconfig.json.
A fallible function is a function that can produce either a useful value or an expected error. Parsing user input, reading configuration, and validating a request are common examples. You could return null, throw an exception, or return an object with optional properties. Each approach can make the caller guess which values are safe to use.
A Result type makes both outcomes explicit:
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };Result<T, E> is a discriminated union. The ok property is the discriminant. Its literal values, true and false, identify the union member. A successful result has a value. A failed result has an error.
Returning a Result
The type parameters describe the two possible payloads:
Tis the success value.Eis the error value.
Here, the function returns a number on success and a string on failure:
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function parsePort(input: string): Result<number, string> {
const port = Number(input);
if (
input.trim() === "" ||
!Number.isInteger(port) ||
port < 0 ||
port > 65535
) {
return { ok: false, error: `Invalid port: ${input}` };
}
return { ok: true, value: port };
}
const result = parsePort("8080");
if (result.ok) {
console.log(`Using port ${result.value}`);
} else {
console.error(result.error);
}Inside the if branch, TypeScript knows that result is the success member, so result.value is available. Inside the else branch, TypeScript knows that result is the error member, so result.error is available.
The compiler prevents you from reading the wrong property:
function printResult(result: Result<number, string>): void {
if (result.ok) {
console.log(result.value);
// result.error is not available here.
} else {
console.log(result.error);
// result.value is not available here.
}
}This design prevents an invalid combination such as “an error with a successful value.” The type has no member containing both properties.
Following the Result through a program
A Result can move through several functions without losing its connection between status and payload.
You can create a reusable helper for errors while preserving the generic success type:
function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T {
if (result.ok) {
return result.value;
}
return fallback;
}
const port = unwrapOr(parsePort("not-a-port"), 3000);
console.log(port);Do not discard the error too early if the caller needs to report it, retry, or choose another action. A Result keeps that decision at the boundary where it belongs.
Common mistakes
A plain boolean does not narrow the payload unless the union members use literal boolean types:
type Good = { ok: true; value: number };
type Bad = { ok: boolean; error?: string };
type NotUseful = Good | Bad;ok: boolean can be either value, so TypeScript cannot reliably connect it to a specific payload. Use ok: true and ok: false in separate members.
Also check the discriminant before reading either payload. Optional properties such as value?: T and error?: E weaken the model because both properties may appear absent or present together.
Exercise
What type does TypeScript assign to result.value inside the true branch of if (result.ok) when result has type Result<number, string>?
Show answer
TypeScript narrows result to { ok: true; value: number }, so result.value has type number.