Last active
January 14, 2023 13:35
-
-
Save gustavonovaes/8b979f82cc7818d716b78eea35d25a5c to your computer and use it in GitHub Desktop.
Example of Either implementation in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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