Skip to content

Instantly share code, notes, and snippets.

@shivam-tripathi
Created February 23, 2022 12:18
Show Gist options
  • Save shivam-tripathi/40b230bb73b2bbc1926a53bb85279be8 to your computer and use it in GitHub Desktop.
Save shivam-tripathi/40b230bb73b2bbc1926a53bb85279be8 to your computer and use it in GitHub Desktop.
Result passing in Typescript
import { Context } from '@src/helpers/context';
import QError from '@src/helpers/error';
import is from 'is_js';
/**
* Contains result which can be error or ok
*/
export default class Result<T> {
private readonly value?: T;
private readonly error?: Error;
private readonly context?: Context;
constructor({ err: error, ok: value, ctx }: { err?: string, ok?: T, ctx?: Context }) {
if ((is.existy(error) && is.existy(value)) || (is.not.existy(error) && is.not.existy(value))) {
throw new QError('Incorrect Result initialization', 'result.INITIALIZE', {
error,
value,
});
}
this.error = new Error(error);
this.value = value;
this.context = ctx;
}
isErr(): boolean {
return is.existy(this.error);
}
isOk(): boolean {
return is.existy(this.value);
}
err(): Error {
if (is.not.existy(this.error)) {
throw new QError('Cannot extract error when it is not present', 'result.ERROR', {
error: this.error,
value: this.value,
});
}
return this.error;
}
ok(): T {
if (is.not.existy(this.value)) {
throw new QError('Cannot extract ok when it is not present', 'result.OK', {
error: this.error,
value: this.value,
});
}
return this.value;
}
ctx(): Context | undefined {
return this.context;
}
static ok<T>(val: T, ctx?: Context): Result<T> {
return new Result<T>({ ok: val, ctx });
}
static err<T>(msg: string, ctx?: Context): Result<T> {
return new Result<T>({ err: msg, ctx });
}
}
@shivam-tripathi
Copy link
Author

shivam-tripathi commented Feb 23, 2022

Example

const okResult = Result.ok({ val: [1,2,3] });
const errResult = Result.err("error string");

if (okResult.isOk()) {
    console.log(okResult.ok()?.val?.map(x => x*2));
}
if (errResult.isErr()) {
    console.log(errResult.err()?.message);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment