Skip to content
jshacks.dev
Patterns

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.

1 min read
Summarize in AI

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.

result.tsTypeScript
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);
  }
}
Text
listening on 8080
bad port: abc

The 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.

Also inTypeScript
Taggednode 24
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.