Last active
October 4, 2019 21:24
-
-
Save fxdave/67454f9fff738f05340d786eb670207d to your computer and use it in GitHub Desktop.
When you want to utilize a rust like Result structure, because it helps you to organize the code better.
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
| function calc(a: number): Result<string, string> { | |
| if (a !== 0) { | |
| return Some("thing") | |
| } else { | |
| return Err("a cannot be zero") | |
| } | |
| } | |
| let result = calc(0) | |
| if(result.error) { | |
| console.error(result.error) | |
| } else { | |
| console.log(result.value) | |
| } |
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
| class Result<T, E> { | |
| value: T | null | |
| error: E | null | |
| } | |
| function Ok<T, E>(val: T): Result<T, E> { | |
| return { | |
| value: val, | |
| error: null | |
| } | |
| } | |
| function Err<T, E>(err: E): Result<T, E> { | |
| return { | |
| value: null, | |
| error: err | |
| } | |
| } | |
| export { Result, Ok, Err } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment