Skip to content

Instantly share code, notes, and snippets.

@laurence-myers
Created April 10, 2018 07:15
Show Gist options
  • Save laurence-myers/77d4e3829c2f0902155fa409a65019ac to your computer and use it in GitHub Desktop.
Save laurence-myers/77d4e3829c2f0902155fa409a65019ac to your computer and use it in GitHub Desktop.
Result: success/failure type union
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 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