Skip to content

Instantly share code, notes, and snippets.

@yazaldefilimone
Created March 1, 2025 22:34
Show Gist options
  • Select an option

  • Save yazaldefilimone/f0490d73b6a103735942fdd86c6cac5a to your computer and use it in GitHub Desktop.

Select an option

Save yazaldefilimone/f0490d73b6a103735942fdd86c6cac5a to your computer and use it in GitHub Desktop.

Revisions

  1. yazaldefilimone created this gist Mar 1, 2025.
    36 changes: 36 additions & 0 deletions either.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    export type Either<L, R> = Left<L, R> | Right<L, R>;

    export class Left<L, R> {
    constructor(private readonly _value: L) {}

    isLeft(): this is Left<L, R> {
    return true;
    }

    isRight(): this is Right<L, R> {
    return false;
    }

    unwrap(): L {
    return this._value;
    }
    }

    export class Right<L, R> {
    constructor(private readonly _value: R) {}

    isLeft(): this is Left<L, R> {
    return false;
    }

    isRight(): this is Right<L, R> {
    return true;
    }

    unwrap(): R {
    return this._value;
    }
    }

    export const left = <L, R>(l: L): Either<L, R> => new Left(l);
    export const right = <L, R>(r: R): Either<L, R> => new Right(r);