Skip to content

Instantly share code, notes, and snippets.

@gustavonovaes
Last active January 14, 2023 13:35
Show Gist options
  • Save gustavonovaes/8b979f82cc7818d716b78eea35d25a5c to your computer and use it in GitHub Desktop.
Save gustavonovaes/8b979f82cc7818d716b78eea35d25a5c to your computer and use it in GitHub Desktop.
Example of Either implementation in Typescript
export class Left<T> {
constructor(public value: T) {}
public isLeft(): this is Left<T> {
return true;
}
public isRight(): this is Right<never> {
return false;
}
public static create<T>(value: T): Left<T> {
return new this(value);
}
}
export class Right<R> {
constructor(public value: R) {}
public isLeft(): this is Left<never> {
return false;
}
public isRight(): this is Right<R> {
return true;
}
public static create<T>(value: T): Right<T> {
return new this(value);
}
}
export type Either<L, R> = Left<L> | Right<R>;
class CustomErrorA extends Error {
constructor() {
super('Custom error A.');
this.name = 'CustomErrorA';
}
}
class CustomErrorB extends Error {
constructor() {
super('Custom error B.');
this.name = 'CustomErrorB';
}
}
interface Result {
random: Number;
}
function checkLucky(): Either<CustomErrorA | CustomErrorB, Result> {
const random = Math.random();
if (random < .2) {
return Left.create(new CustomErrorA());
}
if (random < .5) {
return Left.create(new CustomErrorB());
}
return Right.create({ random });
}
setInterval(() => {
const result = checkLucky();
if (result.isLeft()) {
return console.log('πŸ›‘ Unlucky:', result.value.message )
}
return console.log('πŸ€ Lucky:', result.value.random.toFixed(2))
}, 1000);
/*
> npx ts-node Either.ts
πŸ€ Lucky: 0.64
πŸ€ Lucky: 0.97
πŸ€ Lucky: 0.63
πŸ›‘ Unlucky: Custom error B.
πŸ›‘ Unlucky: Custom error B.
πŸ›‘ Unlucky: Custom error B.
πŸ€ Lucky: 0.82
πŸ€ Lucky: 0.81
πŸ›‘ Unlucky: Custom error A.
πŸ€ Lucky: 0.65
πŸ€ Lucky: 0.93
πŸ›‘ Unlucky: Custom error A.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment