UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

27 lines (25 loc) 730 B
import { FnError } from "../function/FnError.js"; import { dfdlT } from "@monstermann/dfdl"; //#region src/object/getOrThrow.ts /** * `getOrThrow(target, key)` * * Returns the value of `key` property from `target` object, or throws an error if not found or null/undefined. * * ```ts * getOrThrow({ a: 1, b: 2 }, "a"); // 1 * getOrThrow({ a: 1, b: 2 }, "c"); // throws FnError * ``` * * ```ts * pipe({ a: 1, b: 2 }, getOrThrow("a")); // 1 * pipe({ a: 1, b: 2 }, getOrThrow("c")); // throws FnError * ``` */ const getOrThrow = dfdlT((target, key) => { const value = target[key]; if (value != null) return value; throw new FnError("Object.getOrThrow: Value not found.", [target, key]); }, 2); //#endregion export { getOrThrow };