arktypea
arktypeโ€ข11mo ago
papy0977

Fail fast on union type

Hi i try to fail fast on union type as i know if there is an error , it's pointless to continue checking the union and get the right message and not the full list of all union message.
For this i throw an error in the union branch and do a try catch on the type generated. Is there a clever/official way to do that:
function arkTry<T extends (...args: unknown[]) => unknown>(fn: T) {
    return (...args: Parameters<T>): ReturnType<T> | ArkError => {
        try {
            return fn(...args) as ReturnType<T>;
        } catch (e) {
            return e as ArkError;
        }
    };
}

function arkValidOrThrow<T>(x: T): Exclude<T, ArkErrors | ArkError> | never {
    if (x instanceof ArkErrors || x instanceof ArkError) {
        throw new Error(x.message);
    }
    return x as Exclude<T, ArkErrors | ArkError>;
}
Was this page helpful?