Skip to content

Instantly share code, notes, and snippets.

@christianwish
Last active March 12, 2021 12:17
Show Gist options
  • Save christianwish/3a04ccef04bb4526eab01ff9621726ca to your computer and use it in GitHub Desktop.
Save christianwish/3a04ccef04bb4526eab01ff9621726ca to your computer and use it in GitHub Desktop.
Maybe and Either type implementation in TypeScript
type ADT0<T> = [T]
type ADT1<T, V> = [T, V]
// ---------------------------------
type Just<T> = ADT1<'Just:', T>
type Nothing = ADT0<'Nothing:'>
type Maybe<J> = Nothing | Just<J>
// functions
const just = <T>(v: T): Maybe<T> => ['Just:', v];
const nothing = <T>():Maybe<T> => ['Nothing:'];
const isJust = <T>(v: Maybe<T>): v is Nothing => (v[0] === 'Just:');
const isNothing = <T>(v: Maybe<T>): v is Just<T> => (v[0] === 'Nothing:');
// ---------------------------------
type Left<T> = ADT1<'Left:', T>;
type Right<T> = ADT1<'Right:', T>
type Either<L,R> = Left<L> | Right<R>
// functions
const left = <L,R>(v: L):Either<L, R> => ['Left:', v];
const right = <L,R>(v: R):Either<L, R> => ['Right:', v];
const isLeft = <L,R>(v: Either<L, R>): v is Left<L> => (v[0] === 'Left:');
const isRight = <L,R>(v: Either<L, R>): v is Right<R> => (v[0] === 'Right:');
// --------------------------------
const type = <T>(x: [T, ...any]):T => x[0];
// --------------------------------
const x: Either<number, Maybe<string>> = right(just('Hello!'));
const y: Either<number, Maybe<string>> = left(3);
console.log(x); // [ 'Right:', [ 'Just:', 'Hello!' ] ]
console.log(y); // [ 'Left:', 3 ]
console.log(isLeft(x)); // false
console.log(isLeft(y)); // true
console.log(isRight(x)); // true
console.log(isRight(y)); // false
console.log(type(x) === 'Left:'); // false
console.log(type(y) === 'Right:'); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment