Skip to content

Instantly share code, notes, and snippets.

@fxdave
Last active October 4, 2019 21:24
Show Gist options
  • Select an option

  • Save fxdave/67454f9fff738f05340d786eb670207d to your computer and use it in GitHub Desktop.

Select an option

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.
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)
}
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