Skip to content

Instantly share code, notes, and snippets.

@jaketoolson
Created January 26, 2026 22:33
Show Gist options
  • Select an option

  • Save jaketoolson/e1dd53ca7dd5e9ce31404d1a8c24d0f2 to your computer and use it in GitHub Desktop.

Select an option

Save jaketoolson/e1dd53ca7dd5e9ce31404d1a8c24d0f2 to your computer and use it in GitHub Desktop.
type Ok<TOk> = {
kind: 'ok';
value: TOk | null;
};
type Err<TErr> = {
kind: 'err';
value: TErr | null;
errorMessage: string;
exception: Error | null;
code: number | null;
};
export type Result<TOk, TErr = unknown> = Ok<TOk> | Err<TErr>;
export function ok<TOk>(value: TOk | null = null): Ok<TOk> {
return { kind: 'ok', value };
}
export const success = ok; // Alias
export function fail<TErr = unknown>(
errorMessage: string,
codeOrValue?: number | TErr | null,
valueOrException?: TErr | Error | null
): Err<TErr> {
let code: number | null = null;
let value: TErr | null = null;
let exception: Error | null = null;
if (codeOrValue !== undefined) {
if (typeof codeOrValue === 'number') {
code = codeOrValue;
if (valueOrException !== undefined) {
if (valueOrException instanceof Error) {
exception = valueOrException;
} else {
value = valueOrException as TErr;
}
}
} else {
value = codeOrValue as TErr;
if (valueOrException !== undefined) {
if (valueOrException instanceof Error) {
exception = valueOrException;
} else {
throw new Error('When second parameter is a value, third parameter must be an Error or null');
}
}
}
}
return { kind: 'err', value, errorMessage, exception, code };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment