Last active
June 21, 2023 10:26
-
-
Save rawnly/0b80fa62658f52663e4565e31a71f8bf to your computer and use it in GitHub Desktop.
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
// 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