UNPKG

@httpx/assert

Version:
1 lines 2.14 kB
{"version":3,"sources":["../src/object.asserts.ts"],"names":["assertPlainObject","v","msgOrErrorFactory","isPlainObject","createAssertException","formatErrMsg"],"mappings":"8KA4CO,SAASA,CAAAA,CAGdC,CAAAA,CACAC,CAAAA,CAGsB,CACtB,GAAI,CAACC,aAAAA,CAAsBF,CAAC,CAAA,CAC1B,MAAMG,qBAAAA,CACJF,CAAAA,CACAG,YAAAA,CAAa,cAAA,CAAgBJ,CAAC,CAChC,CAEJ","file":"object.asserts.mjs","sourcesContent":["import { formatErrMsg } from './messages/errorMessages';\nimport { isPlainObject } from './object.guards';\nimport type {\n BasePlainObject,\n DefaultBasePlainObject,\n} from './object.internal.types';\nimport type { PlainObject } from './object.types';\nimport type { MsgOrErrorFactory } from './types/internal.types';\nimport { createAssertException } from './utils/createAssertException';\n/**\n * Assert a value is a plain object\n *\n * @example\n * ```typescript\n * import { assertPlainObject } from '@httpx/plain-object';\n * import type { PlainObject } from '@httpx/plain-object';\n *\n * function fn(value: unknown) {\n *\n * // 👇 Throws `new TypeError('Not a plain object')` if not a plain object\n * assertPlainObject(value);\n *\n * // 👇 Throws `new TypeError('Custom message')` if not a plain object\n * assertPlainObject(value, 'Custom message');\n *\n * // 👇 Throws custom error if not a plain object\n * assertPlainObject(value, () => {\n * throw new HttpBadRequest('Custom message');\n * });\n *\n * return value;\n * }\n *\n * try {\n * const value = fn({ key: 'value' });\n * // ✅ Value is known to be PlainObject<unknown>\n * assertType<PlainObject>(value);\n * } catch (error) {\n * console.error(error);\n * }\n * ```\n *\n * @throws TypeError\n */\nexport function assertPlainObject<\n TValue extends BasePlainObject = DefaultBasePlainObject,\n>(\n v: unknown,\n msgOrErrorFactory?: MsgOrErrorFactory\n): asserts v is TValue extends DefaultBasePlainObject\n ? BasePlainObject\n : PlainObject<TValue> {\n if (!isPlainObject<TValue>(v)) {\n throw createAssertException(\n msgOrErrorFactory,\n formatErrMsg('plain object', v)\n );\n }\n}\n"]}