Skip to content

Instantly share code, notes, and snippets.

@KEIII
Last active April 14, 2020 16:36
Show Gist options
  • Save KEIII/a7d09b745db1590a4e1c5a6601781add to your computer and use it in GitHub Desktop.
Save KEIII/a7d09b745db1590a4e1c5a6601781add to your computer and use it in GitHub Desktop.
Rust like Result and Option type for TypeScript
export type Ok<T> = { _tag: "Ok"; ok: T };
export type Err<E> = { _tag: "Err"; err: E };
export type Result<T, E> = Ok<T> | Err<E>;
const Ok = <T, E>(ok: T): Result<T, E> => ({ _tag: "Ok", ok });
const Err = <T, E>(err: E): Result<T, E> => ({ _tag: "Err", err });
export const Result = Object.freeze({ Ok, Err });
export type Some<T> = { _tag: "Some"; some: T };
export type None = { _tag: "None" };
export type Option<T> = Some<T> | None;
const Some = <T>(some: T): Option<T> => ({ _tag: "Some", some });
const None = <T>(): Option<T> => ({ _tag: "None" });
export const Option = Object.freeze({ Some, None });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment