Skip to content

Instantly share code, notes, and snippets.

@rawnly
Last active June 21, 2023 10:26
Show Gist options
  • Save rawnly/0b80fa62658f52663e4565e31a71f8bf to your computer and use it in GitHub Desktop.
Save rawnly/0b80fa62658f52663e4565e31a71f8bf to your computer and use it in GitHub Desktop.
// Given this type
type ResultSuccess<T> = {
data: T
success: true
}
type ResultFailure<E> = {
error: E
success: false
}
type Result<T, E> = ResultSuccess<T> | ResultFailure<E>
const Result = {
success: <T>(data: T): ResultSuccess<T> => ({ data, success: true }),
failure: <E>(error: E): ResultFailure<E> => ({ error, success: false }),
isSuccess: <T, E>(result: Result<T, E>): result is ResultSuccess<T> => result.success,
isFailure: <T, E>(result: Result<T, E>): result is ResultFailure<E> => !result.success,
}
// assertion handler
type HandleResultFailure = <T, E>(result: Result<T, E>) => asserts result is ResultSuccess<T>
const handleResultFailure: HandleResultFailure = (result) => {
if (Result.isSuccess(result)) return
throw new Error('FAIL')
}
// CASE 1
// Standard handling
function standardWay() {
const result: Result<number, Error> = Result.success(1) as any
// standard way
if (result.success === false) {
console.error(result.error)
return
}
console.log(result.data)
}
// CASE 2
// Assertion way
function assertionWay() {
const result: Result<number, Error> = Result.success(1) as any
handleResultFailure(result)
console.log(result.data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment