@monstermann/fn
Version:
A utility library for TypeScript.
28 lines (26 loc) • 731 B
JavaScript
import { FnError } from "../function/FnError.js";
import { dfdlT } from "@monstermann/dfdl";
//#region src/option/orThrow.ts
/**
* `orThrow(target)`
*
* Returns the target value if it's not `null` or `undefined`, otherwise throws an error. This function is useful for asserting that a value is not null or undefined.
*
* ```ts
* orThrow(5); // 5
* orThrow("hello"); // "hello"
* orThrow(null); // throws FnError
* orThrow(undefined); // throws FnError
* ```
*
* ```ts
* pipe(5, orThrow()); // 5
* pipe(null, orThrow()); // throws FnError
* ```
*/
const orThrow = dfdlT((target) => {
if (target != null) return target;
throw new FnError("Nullable.orThrow: Value was nullable.", [target]);
}, 1);
//#endregion
export { orThrow };