Page MenuHomeSealhub

with-fallback.ts
No OneTemporary

with-fallback.ts

// use this to more concisely define values with one or more fallbacks to use when they are null.
// If called with two args, the second one has to be non-null
// if called with three args, the third one has to be non-null
//
// in two-arg mode, if the first argument is not null, then it's returned and fallback is not used.
// if the first argument is null, then the second arg is returned
//
// in three-arg mode, the first value is never returned. If the first arg is not-null, then the second arg is returned (if it's not null). Otherwise the third arg is returned
export function withFallback<T1, T2 extends NonNullable<unknown>>(
value1: T1,
value2: T2
): NonNullable<T1> | T2;
export function withFallback<T1, T2, T3 extends NonNullable<unknown>>(
value1: T1,
value2: T2,
value3?: T3
): NonNullable<T2> | T3;
export function withFallback<T1, T2, T3 extends NonNullable<unknown>>(
value1: T1,
value2: T2,
value3?: T3
): NonNullable<T1> | NonNullable<T2> | T3 {
if (value3 !== undefined) {
// three arg mode
if (
value1 !== null &&
value1 !== undefined &&
value2 !== null &&
value2 !== undefined
) {
return value2;
} else {
return value3;
}
} else {
// two arg mode
if (value1 !== null && value1 !== undefined) {
return value1;
} else if (value2 !== undefined && value2 !== null) {
return value2;
} else {
throw new Error("No suitable fallback: ${arguments}");
}
}
}

File Metadata

Mime Type
text/plain
Expires
Tue, Jul 8, 07:53 (14 h, 54 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
625901
Default Alt Text
with-fallback.ts (1 KB)

Event Timeline