Skip to content
jshacks.dev
Patterns

Implement an option type in TypeScript

Implement an option type in TypeScript: a tagged value that is either some value or none, so absence is explicit. Node.js 24.

1 min read
Summarize in AI

null and undefined slip through when you forget a check. An option type makes a value that may be missing a distinct type that you have to open.

option.tsTypeScript
type Option<T> = { some: true; value: T } | { some: false };

const some = <T>(value: T): Option<T> => ({ some: true, value });
const none: Option<never> = { some: false };

const find = <T>(items: T[], test: (item: T) => boolean): Option<T> => {
  const index = items.findIndex(test);
  return index === -1 ? none : some(items[index]);
};

const unwrapOr = <T>(option: Option<T>, fallback: T): T => (option.some ? option.value : fallback);

const names = ['ada', 'grace'];
console.log(unwrapOr(find(names, (n) => n.startsWith('g')), 'nobody'));
console.log(unwrapOr(find(names, (n) => n.startsWith('z')), 'nobody'));
Text
grace
nobody

find returns an Option instead of T | undefined, and unwrapOr is the one place that opens it. Unlike undefined, an option can wrap undefined or null as a real value.

Often T | undefined with strictNullChecks and ?? does the same job with less code. Use an option when a missing value is itself a valid answer you need to tell apart from "absent". Node.js 24 strips the types when it runs the file.

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.