After rewriting my utils script for typescript one too many times, I finally decided to move my shared logic between NPM packages onto a public package! This package is likely to share a lot of logic with other packages, but the difference is… this one is mine.
I added some Result Type I found myself using quite a bit.
type SafelyError<E> = Error & {
readonly __brand: "safely";
readonly __error: E;
};
type SafelyResultSuccess<T> = { ok: true; value: T };
type SafelyResultFailure<E> = { ok: false; error: SafelyError<E> };
export type SafelyResult<T = unknown, E = unknown> =
| SafelyResultSuccess<T>
| SafelyResultFailure<E>;
As well as a try catch type wrapper for those new types
export function safelyRun<K extends SafelyFunc, E = unknown>(
func: K,
...args: Parameters<K>
): SafelyResult<ReturnType<K>, E> {
try {
const data = func(...args);
return { ok: true, value: data } as SafelyResult<ReturnType<K>, E>;
} catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
return { ok: false, error: error as SafelyError<E> };
}
}
Among other features I plan to add to this package as I need them. I am currently working on a json literal type parser for the “json-schema” package, in order to convert literal schema’s into expected types. But we’ll see as time goes on. If you want to find this package, it is publicly available at https://www.npmjs.com/package/@aonyxlimited/typelib
Leave a Reply