Created
April 10, 2018 07:15
-
-
Save laurence-myers/77d4e3829c2f0902155fa409a65019ac to your computer and use it in GitHub Desktop.
Result: success/failure type union
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
interface IFoo { | |
bar : string; | |
} | |
function validateSomething(obj : IFoo) : Result<string, IFoo> { | |
if (obj.bar.length === 0) { | |
return resultFailure("You must provide at least one object"); | |
} else { | |
return resultSuccess(obj); | |
} | |
} |
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
// This is a poor man's "Either", without any monadic capabilities. | |
export interface Success<TValue> { | |
success: true; | |
value: TValue; | |
} | |
export interface Failure<TFailure> { | |
success: false; | |
failure: TFailure; | |
} | |
export type Result<TFailure, TValue> = Failure<TFailure> | Success<TValue>; | |
// Below are some convenience functions to reduce boilerplate, or make it more DSL-y. (Otherwise you might need to cast "true" to "true", instead of letting it be typed to "boolean") | |
export function resultSuccess<T>(value: T): Success<T> { | |
return { | |
success: true, | |
value | |
}; | |
} | |
export function resultFailure<T>(failure: T): Failure<T> { | |
return { | |
success: false, | |
failure | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment