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.
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.
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'));grace
nobodyfind 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.