I built a small type-level library to simplify writing pairs of functions of the form
function a(...): T | undefined;
function b(...): T;
where b is derived from a by throwing an exception if undefined is returned. The basic idea is as follows:
export enum FailMode { CanFail, CanNotFail }
export const canFail = FailMode.CanFail;
export const canNotFail = FailMode.CanNotFail
export type Failure<F extends FailMode> = F extends FailMode.CanFail ? undefined : never;
export type Maybe<T, F extends FailMode> = T | Failure<F>;
export function failure<F extends FailMode>(mode: F): Failure<F> {
if (mode === canFail) return undefined as Failure<F>;
throw new Error("failure");
}
Now we can combine a
and b
into a single function that takes one extra parameter to distinguish the types:
function upperCaseIfYouCan<F extends FailMode>(x: string | undefined, mode: F): Maybe<string, F> {
if (x === undefined)
return failure<F>(mode);
return x.toUpperCase();
}
// both of these now work
let y: string = upperCaseIfYouCan("foo", canNotFail); // can throw, but will never return undefined
let z: string | undefined = upperCaseIfYouCan("foo", canFail); // cannot throw, but can return undefined
Now in most cases I want the canNotFail
variant, and I'm wondering if there is a way to make this the "default" in that I don't have to pass the canNotFail
parameter in that case, so that the following would work:
let y: string = upperCaseIfYouCan("foo"); // can throw
I already determined that this cannot be achieved via default arguments, because the type of the default argument must be unifiable with F
. Is there a way to achieve this in a different way, such that defining functions like upperCaseIfYouCan
is similarly easy?