Skip to content

Instantly share code, notes, and snippets.

@eczn
Created February 1, 2025 20:07
Show Gist options
  • Save eczn/d714cd297e29e7c415dec70066ad9845 to your computer and use it in GitHub Desktop.
Save eczn/d714cd297e29e7c415dec70066ad9845 to your computer and use it in GitHub Desktop.
TypeScript Option<T>
enum TypeNone { }
export type None = { type: typeof TypeNone };
function None<T>(d: T): None { return { type: TypeNone } };
function isNone(x: any): x is None { return !!(x && x.type === TypeNone) };
enum TypeSome { }
export type Some<T> = { type: typeof TypeSome, data: [_: T] };
function Some<T>(d: T): Some<T> { return { type: TypeSome, data: [d] } };
function isSome(x: any): x is Some<unknown> { return !!(x && x.type === TypeSome && x.data) };
export const Option = {
None, isNone, Some, isSome,
}
export type Option<T> = (
| None
| Some<T>
);
import { Option } from './examples/option.enum';
export function handle(maybe: Option<number>) {
if (Option.isSome(maybe)) {
const [val] = maybe.data; // val is number
return;
}
maybe // ⬅️ None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment