Skip to content

Instantly share code, notes, and snippets.

@rogeriomq
Last active January 24, 2025 00:32
Show Gist options
  • Save rogeriomq/be9a0bc28c8123082f6976edb75f34d0 to your computer and use it in GitHub Desktop.
Save rogeriomq/be9a0bc28c8123082f6976edb75f34d0 to your computer and use it in GitHub Desktop.
Result Patter with Typescript. Inspired By result.dart of the flutter architecture guide.
class Success<T> {
readonly isOk = true;
readonly isFailure = false;
value: T;
constructor(value: T) {
this.value = value;
}
}
class Failure<E> {
readonly isOk = false;
readonly isFailure = true;
error: E;
constructor(error: E) {
this.error = error;
}
}
export type Result<T, E> = Success<T> | Failure<E>;
export const failure = <E>(e: E): Failure<E> => new Failure(e);
export const success = <T>(t: T): Success<T> => new Success(t);
/*
// Code example:
const apiGet = (): Result<string, Error> => {
try {
const response = 'response';
return success(response);
} catch (error) {
return failure(new Error('Error getting data'));
}
}
const result = apiGet();
if(result.isOk()) {
console.log(result.value);
} else {
console.log(result.error);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment