Skip to content

Instantly share code, notes, and snippets.

@assainov
Last active November 18, 2024 14:41
Show Gist options
  • Save assainov/1d4c6d925fe613ccf3828f9ee13d9490 to your computer and use it in GitHub Desktop.
Save assainov/1d4c6d925fe613ccf3828f9ee13d9490 to your computer and use it in GitHub Desktop.
Result type in TypeScript
type Success<T> = { isSuccess: true; data: T};
type Failure<E> = { isSuccess: false; error: E };
export type Result<T, E> = Success<T> | Failure<E>;
export const result = {
succeed<T>(data: T) {
return { isSuccess: true, data } as Success<T>;
},
fail<E>(error: E) {
return { isSuccess: false, error } as Failure<E>;
}
};
// DEMO
function doSomething(fail: boolean): Result<{message: string}, string> {
if (fail) return result.fail('Something went wrong');
return result.succeed({ message: 'Success' });
}
(function main() {
const result = doSomething(false);
// isSuccess determines whether it's a failure or not
if (!result.isSuccess) {
const error: string = result.error;
console.log(result.error.toString());
console.log(error);
return;
}
// result.data is not undefined because isSuccess is guaranteed to be true
const data: {message: string} = result.data; // no ts error
console.log(data);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment