Last active
August 13, 2023 01:08
-
-
Save sallar/b66467428a9015711509f70f40e4d233 to your computer and use it in GitHub Desktop.
TypeScript Either / Pattern Matching
This file contains 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
import { Either, Left, Right, match } from './patterns.ts'; | |
interface Person { | |
name: string; | |
} | |
const readValueFromAPI = (): Either<Error, Person> => { | |
// ... | |
const person: Person = { | |
name: 'Test', | |
}; | |
return Right(person); // or Left(new Error('Something happened...')); | |
}; | |
const str = match( | |
readValueFromAPI(), | |
(err) => err.message, | |
(person) => person.name, | |
); |
This file contains 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 type Left<T> = { tag: 'left'; value: T }; | |
export type Right<T> = { tag: 'right'; value: T }; | |
export type Either<L, R> = Left<L> | Right<R>; | |
export const match = <T, L, R>( | |
input: Either<L, R>, | |
left: (left: L) => T, | |
right: (right: R) => T, | |
) => { | |
switch (input.tag) { | |
case 'left': | |
return left(input.value); | |
case 'right': | |
return right(input.value); | |
} | |
}; | |
export const isRight = <L, R>(input: Either<L, R>): input is Right<R> => { | |
return input.tag === 'right'; | |
}; | |
export const isLeft = <L, R>(input: Either<L, R>): input is Left<L> => { | |
return input.tag === 'left'; | |
}; | |
export const Right = <T>(value: T): Right<T> => { | |
return { | |
tag: 'right', | |
value, | |
}; | |
}; | |
export const Left = <T>(value: T): Left<T> => { | |
return { | |
tag: 'left', | |
value, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment