Implement a typed result object in TypeScript
Implement a typed result object in TypeScript: a discriminated union makes the compiler force you to handle the error. Node.js 24.
A result type returns success or failure as data. With a discriminated union, TypeScript will not let you read the value until you have checked it succeeded.
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
function parsePort(input: string): Result<number, string> {
const port = Number(input);
return Number.isInteger(port) && port > 0 ? ok(port) : err(`bad port: ${input}`);
}
for (const input of ['8080', 'abc']) {
const result = parsePort(input);
if (result.ok) {
console.log('listening on', result.value);
} else {
console.log(result.error);
}
}listening on 8080
bad port: abcThe ok field is the discriminant. Inside the if (result.ok) branch TypeScript knows value exists, and in the else branch it knows error does. Writing result.value before the check is a compile error.
Node.js 24 runs this file as it is by stripping the types, so run tsc --noEmit to see the errors. The type is erased at run time, so the check protects only code that is type-checked.