Created
April 18, 2023 15:01
-
-
Save arthurgubaidullin/23ff6751c558a27e8d54dee5f145dd3e to your computer and use it in GitHub Desktop.
An example of using the Either type
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
import * as E from 'fp-ts/Either'; | |
// 1. | |
const MY_VAR_UNSAFE: string | undefined = process.env['MY_VAR']; | |
const MY_VAR_NOT_DEFINED = 'Environment variable MY_VAR not set.' as const; | |
const MY_VAR_EITHER: E.Either<typeof MY_VAR_NOT_DEFINED, string> = | |
MY_VAR_UNSAFE !== undefined | |
? E.right(MY_VAR_UNSAFE) | |
: E.left(MY_VAR_NOT_DEFINED); | |
const main = () => { | |
if (E.isLeft(MY_VAR_EITHER)) { | |
console.error(MY_VAR_EITHER.left); | |
return; | |
} | |
console.log(MY_VAR_EITHER.right); | |
}; | |
main(); | |
// 2. | |
export const div = ( | |
a: number, | |
b: number | |
): E.Either<'Division by zero.', number> => { | |
if (b === 0) { | |
return E.left('Division by zero.' as const); | |
} | |
return E.right(a / b); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment