### Get String Value by Path Source: https://context7.com/voxpelli/typed-utils/llms.txt Retrieves a string value from an object using a dot-notation path. Returns `false` if the value is not a string, and `undefined` if the path does not exist. ```javascript import { getStringValueByPath } from '@voxpelli/typed-utils'; const config = { app: { name: 'MyApp', version: 123, // number, not string description: null } }; // Get string value const name = getStringValueByPath(config, 'app.name'); console.log(name); // 'MyApp' // Returns false for non-string const version = getStringValueByPath(config, 'app.version'); console.log(version); // false // Returns undefined for missing path const missing = getStringValueByPath(config, 'app.author'); console.log(missing); // undefined ``` -------------------------------- ### Exhaustive type checking with assertTypeIsNever Source: https://github.com/voxpelli/typed-utils/blob/main/README.md This example demonstrates how assertTypeIsNever now returns `never`, allowing for correct exhaustive narrowing in TypeScript switch or if chains. ```typescript function process(val: string | number | { key: string }): string { if (isType(val, 'string')) return val; if (isType(val, 'number')) return String(val); if (isType(val, 'object')) return val.key; assertTypeIsNever(val); // now works — val is never } ``` -------------------------------- ### Create and use a FrozenSet Source: https://context7.com/voxpelli/typed-utils/llms.txt Demonstrates initializing a FrozenSet, performing read operations, and handling mutation attempts that throw errors. ```javascript import { FrozenSet } from '@voxpelli/typed-utils'; // Create an immutable set const VALID_STATUSES = new FrozenSet(['pending', 'active', 'completed', 'archived']); // Read operations work normally console.log(VALID_STATUSES.has('active')); // true console.log(VALID_STATUSES.size); // 4 // Iteration works for (const status of VALID_STATUSES) { console.log(status); } // Spread works const statusArray = [...VALID_STATUSES]; // ['pending', 'active', 'completed', 'archived'] // Mutations throw try { VALID_STATUSES.add('deleted'); } catch (err) { console.log(err.message); // 'Cannot modify frozen set' } try { VALID_STATUSES.delete('pending'); } catch (err) { console.log(err.message); // 'Cannot modify frozen set' } // Create from existing Set const mutableSet = new Set([1, 2, 3]); const immutableSet = new FrozenSet([...mutableSet]); // Changes to mutableSet won't affect immutableSet ``` -------------------------------- ### Miscellaneous Utilities Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Utility functions for variable explanation and object manipulation. ```APIDOC ## explainVariable(value) ### Description Returns a `typeof` style explanation of a variable, with added support for eg. `null` and `array`. ### Method UTILITY ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **value** (any) - Required - The variable to explain. ## looksLikeAnErrnoException(err) ### Description Returns `true` if the `err` looks like being of the `NodeJS.ErrnoException` type. ### Method UTILITY ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **err** (any) - Required - The error to check. ## omit(obj, keys) ### Description The TypeScript utility type [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) with code that does the actual omit. ### Method UTILITY ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to omit keys from. - **keys** (string | number | symbol | Array) - Required - The keys to omit. ## pick(obj, keys) ### Description The TypeScript utility type [`Pick`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys) with code that does the actual pick. ### Method UTILITY ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to pick keys from. - **keys** (string | number | symbol | Array) - Required - The keys to pick. ``` -------------------------------- ### Create object subsets with pick Source: https://context7.com/voxpelli/typed-utils/llms.txt Creates a new object containing only the specified keys, providing runtime implementation for TypeScript's Pick utility. ```javascript import { pick } from '@voxpelli/typed-utils'; const user = { id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin', createdAt: '2024-01-01' }; const credentials = pick(user, ['email', 'name']); // Result: { email: 'alice@example.com', name: 'Alice' } // Type: Pick const identity = pick(user, ['id', 'name', 'role']); // Result: { id: 1, name: 'Alice', role: 'admin' } ``` -------------------------------- ### Type Utilities Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Utilities for compile-time type validation and exhaustive checks. ```APIDOC ## assertTypeIsNever(value, [message]) ### Description Asserts that a value is of type `never`. Throws an error at runtime if reached. ## noopTypeIsAssignableToBase(base, superset) ### Description Validates at compile-time that `superset` is assignable to `base`. ## noopTypeIsEmptyObject(base, shouldHaveKeys) ### Description Validates at compile-time that `base` is an empty object. ## noopTypeIsNever(value) ### Description Validates at compile-time that `value` is `never` without throwing at runtime. ``` -------------------------------- ### Object Key Utilities Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Utilities for retrieving keys from objects with improved TypeScript support for union types. ```APIDOC ## typedObjectKeys(obj) ### Description Returns the keys of an object as `Array`. For union types, it resolves to keys shared between all objects in the union. ### Parameters #### Request Body - **obj** (object) - Required - The object to extract keys from. ## typedObjectKeysAll(obj) ### Description Similar to `typedObjectKeys`, but resolves to all possible keys within a union type. ### Parameters #### Request Body - **obj** (object) - Required - The object to extract keys from. ``` -------------------------------- ### Type Assertion Utilities Source: https://context7.com/voxpelli/typed-utils/llms.txt Utilities for compile-time type checking and assertions. ```APIDOC ## assertTypeIsNever(value, [message]) ### Description Asserts that a value is of type `never`, used for exhaustive switch/conditional checks. Throws at runtime if reached, indicating an unhandled case. ### Parameters #### Path Parameters - **value** (never) - Required - The value to assert as never. - **message** (string) - Optional - A custom message for the error. ### Request Example ```javascript import { assertTypeIsNever } from '@voxpelli/typed-utils'; function getColorHex(color) { switch (color) { case 'red': return '#ff0000'; case 'green': return '#00ff00'; case 'blue': return '#0000ff'; default: assertTypeIsNever(color, `Unhandled color: ${color}`); } } ``` ``` ```APIDOC ## noopTypeIsNever(value) ### Description No-op function that validates at compile-time that value is `never`. Does nothing at runtime. Non-throwing alternative to `assertTypeIsNever()`. ### Parameters #### Path Parameters - **value** (never) - Required - The value to assert as never. ### Request Example ```javascript import { noopTypeIsNever } from '@voxpelli/typed-utils'; function handleStatus(status) { switch (status) { case 'pending': return 'Waiting...'; case 'complete': return 'Done!'; default: noopTypeIsNever(status); return 'Unknown'; } } ``` ``` ```APIDOC ## noopTypeIsAssignableToBase(base, superset) ### Description No-op function that validates at compile-time that Superset type is assignable to Base type. Useful for type tests. ### Parameters #### Path Parameters - **base** (type) - Required - The base type. - **superset** (type) - Required - The superset type. ### Request Example ```javascript import { noopTypeIsAssignableToBase } from '@voxpelli/typed-utils'; const baseType = { name: '' }; const superType = { name: '', age: 0 }; noopTypeIsAssignableToBase(baseType, superType); ``` ``` ```APIDOC ## noopTypeIsEmptyObject(base, shouldHaveKeys) ### Description No-op function that validates at compile-time that Base type is an empty object. Useful for type tests. ### Parameters #### Path Parameters - **base** (object) - Required - The object type to check. - **shouldHaveKeys** (boolean) - Required - Whether the object should be empty (true) or not (false). ### Request Example ```javascript import { noopTypeIsEmptyObject } from '@voxpelli/typed-utils'; const emptyObj = {}; noopTypeIsEmptyObject(emptyObj, true); ``` ``` -------------------------------- ### assertOptionalKeyWithType Source: https://context7.com/voxpelli/typed-utils/llms.txt Asserts that an object either doesn't contain the key, or if present, the value is undefined or of the given type. ```APIDOC ## assertOptionalKeyWithType(obj, key, type) ### Description Asserts that an object either doesn't contain the key, or if present, the value is undefined or of the given type. ### Method N/A (This is a utility function, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { assertOptionalKeyWithType } from '@voxpelli/typed-utils'; function parseOptions(options) { assertOptionalKeyWithType(options, 'timeout', 'number'); assertOptionalKeyWithType(options, 'retries', 'number'); // options may have timeout?: number and retries?: number return { timeout: options.timeout ?? 5000, retries: options.retries ?? 3 }; } console.log(parseOptions({})); // { timeout: 5000, retries: 3 } console.log(parseOptions({ timeout: 10000 })); // { timeout: 10000, retries: 3 } // parseOptions({ timeout: 'slow' }); // Throws ``` ### Response #### Success Response (200) N/A (This function throws an error on failure and returns void on success) #### Response Example None ``` -------------------------------- ### explainVariable Source: https://context7.com/voxpelli/typed-utils/llms.txt Provides a `typeof`-like explanation of a variable, distinguishing `null` and `array` from generic `object`. ```APIDOC ## explainVariable(value) ### Description Returns a `typeof`-style explanation of a variable, with added support for `null` and `array` as distinct types. ### Parameters #### Path Parameters - **value** (any) - Required - The variable to explain. ### Request Example ```javascript import { explainVariable } from '@voxpelli/typed-utils'; console.log(explainVariable('hello')); // 'string' console.log(explainVariable(42)); // 'number' console.log(explainVariable(true)); // 'boolean' console.log(explainVariable(null)); // 'null' console.log(explainVariable([1, 2, 3])); // 'array' console.log(explainVariable({ a: 1 })); // 'object' console.log(explainVariable(undefined)); // 'undefined' console.log(explainVariable(() => {})); // 'function' ``` ``` -------------------------------- ### isOptionalKeyWithType Source: https://context7.com/voxpelli/typed-utils/llms.txt Checks if an object either doesn't contain a key, or the value is undefined or of a specific type. ```APIDOC ## isOptionalKeyWithType(obj, key, type) ### Description Returns true if the object either doesn't contain the key, or the value is undefined or of the given type. ### Parameters #### Arguments - **obj** (object) - The object to check. - **key** (string | number | symbol) - The key of the property to check. - **type** (string) - The expected type of the property's value if the key exists and the value is not undefined. ### Returns - (boolean) - True if the condition is met, false otherwise. ### Example ```javascript import { isOptionalKeyWithType } from '@voxpelli/typed-utils'; function validateOptions(options) { if (!isOptionalKeyWithType(options, 'port', 'number')) { return { valid: false, error: 'port must be a number' }; } if (!isOptionalKeyWithType(options, 'host', 'string')) { return { valid: false, error: 'host must be a string' }; } return { valid: true }; } console.log(validateOptions({})); // { valid: true } console.log(validateOptions({ port: 3000 })); // { valid: true } console.log(validateOptions({ port: 'invalid' })); // { valid: false, error: 'port must be a number' } ``` ``` -------------------------------- ### Assert Object Key With Type Source: https://context7.com/voxpelli/typed-utils/llms.txt Use to verify that an object has a specific key and that its value conforms to a given type. Useful for validating structured data. ```javascript import { assertKeyWithType } from '@voxpelli/typed-utils'; function processUser(data) { assertKeyWithType(data, 'name', 'string'); assertKeyWithType(data, 'age', 'number'); // data is now Record<'name', string> & Record<'age', number> return `${data.name} is ${data.age} years old`; } console.log(processUser({ name: 'Alice', age: 30 })); // 'Alice is 30 years old' // assertKeyWithType({ name: 123 }, 'name', 'string'); // Throws: Expected key "name" to have type "string", but got: number ``` -------------------------------- ### Assert Optional Object Key With Type Source: https://context7.com/voxpelli/typed-utils/llms.txt Use to assert that an object key is either absent or, if present, its value matches the specified type. This helps in handling optional properties safely. ```javascript import { assertOptionalKeyWithType } from '@voxpelli/typed-utils'; function parseOptions(options) { assertOptionalKeyWithType(options, 'timeout', 'number'); assertOptionalKeyWithType(options, 'retries', 'number'); // options may have timeout?: number and retries?: number return { timeout: options.timeout ?? 5000, retries: options.retries ?? 3 }; } console.log(parseOptions({})); // { timeout: 5000, retries: 3 } console.log(parseOptions({ timeout: 10000 })); // { timeout: 10000, retries: 3 } // parseOptions({ timeout: 'slow' }); // Throws ``` -------------------------------- ### Assertion Helpers Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Custom error classes and assertion functions for runtime type checking. ```APIDOC ## TypeHelpersAssertionError ### Description Custom error class thrown by all assertion helpers in this module. You can catch this error type to specifically handle assertion failures from these utilities. ### Response #### Success Response (200) - **error** (TypeHelpersAssertionError) - An instance of the custom error class. ### Response Example ```json { "example": "new TypeHelpersAssertionError('Assertion failed')" } ``` ``` ```APIDOC ## TypeHelpersAssertionEqualityError ### Description Custom error class thrown by equality assertions such as `assertStrictEqual(actual, expected, [message])`. ### Response #### Success Response (200) - **error** (TypeHelpersAssertionEqualityError) - An instance of the custom equality error class. ### Response Example ```json { "example": "new TypeHelpersAssertionEqualityError('Values not equal')" } ``` ``` ```APIDOC ## assert(condition, message) ### Description Throws a `TypeHelpersAssertionError` if `condition` is falsy. Used internally by other assertion helpers, but can also be used directly for custom runtime assertions. ### Parameters #### Path Parameters - **condition** (boolean) - Required - The condition to assert. - **message** (string) - Optional - The error message to display if the assertion fails. ### Response #### Success Response (200) - **assertionResult** (void) - No return value on success, throws error on failure. ### Response Example ```json { "example": "assert(1 === 1, 'Numbers should be equal')" } ``` ``` -------------------------------- ### Create and use FrozenSet Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Use FrozenSet for immutable set operations. It provides a Set API but prevents modifications after creation by throwing TypeErrors. ```javascript import { FrozenSet } from '@voxpelli/typed-utils'; const COLORS = new FrozenSet(['red', 'green', 'blue']); COLORS.has('red'); // true COLORS.size; // 3 COLORS.add('purple'); // throws TypeError: Cannot modify frozen set ``` ```javascript const regular = new Set([1, 2, 3]); const frozen = new FrozenSet(regular); // copies current contents; further changes to `regular` won't affect `frozen` ``` -------------------------------- ### Extract all union keys with typedObjectKeysAll Source: https://context7.com/voxpelli/typed-utils/llms.txt Returns all possible keys from any member of a union type. ```javascript import { typedObjectKeysAll } from '@voxpelli/typed-utils'; // With union types function getKeys(obj) { return typedObjectKeysAll(obj); // Returns all keys from either shape in the union } const shapeA = { kind: 'a', value: 1 }; const shapeB = { kind: 'b', label: 'hi' }; // For single objects, works like typedObjectKeys const keys = typedObjectKeysAll(shapeA); // Type: Array<'kind' | 'value'> ``` -------------------------------- ### assert(condition, message) Source: https://context7.com/voxpelli/typed-utils/llms.txt Performs a runtime assertion, throwing a TypeHelpersAssertionError if the condition is falsy. ```APIDOC ## assert(condition, message) ### Description Throws a `TypeHelpersAssertionError` if the condition is falsy. Used internally by other assertion helpers and can be used directly for custom runtime assertions. ### Parameters - **condition** (any) - Required - The condition to evaluate. - **message** (string) - Optional - The error message to throw if the assertion fails. ``` -------------------------------- ### Array Helpers Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Utility functions for manipulating and type-guarding arrays. ```APIDOC ## filter(inputArray, [valueToRemove]) => filteredArray ### Description Takes an array as `inputArray` and a `valueToRemove` that is a string literal, `false`, `null` or `undefined`, defaulting to `undefined` if left out. Creates a new array with all values from `inputArray` except the one that matches `valueToRemove`, then returns that array with a type where the `valueToRemove` type has also been removed from the possible values. ### Parameters #### Path Parameters - **inputArray** (Array) - Required - The input array to filter. - **valueToRemove** (string | false | null | undefined) - Optional - The value to remove from the array. ### Request Example ```javascript import { filter } from '@voxpelli/typed-utils'; /** @type {string[]} */ const noUndefined = filter(['foo', undefined]); ``` ### Response #### Success Response (200) - **filteredArray** (Array) - The new array with the specified value removed and its type narrowed. ### Response Example ```json { "example": "['foo']" } ``` ``` ```APIDOC ## filterWithCallback(value, callback) ### Description Similar to `Array.prototype.filter()` but expects the `callback` to be a function like `(value: unknown) => value is any` where the `is` is the magic sauce. ### Parameters #### Path Parameters - **value** (any) - Required - The value to filter. - **callback** ((value: unknown) => value is any) - Required - The callback function used for filtering. ### Response #### Success Response (200) - **filteredArray** (Array) - The filtered array. ### Response Example ```json { "example": "[filtered_items]" } ``` ``` ```APIDOC ## isArrayOfType(value, callback) ### Description Similar to `Array.isArray()` but also checks that the array only contains values of type verified by the `callback` function and sets the type to be an array of that type rather than simply `any[]`. The `callback` should be a function like `(value: unknown) => value is any` and needs to have an `is` in the return type for the types to work. ### Parameters #### Path Parameters - **value** (any) - Required - The value to check. - **callback** ((value: unknown) => value is any) - Required - The callback function to verify array element types. ### Response #### Success Response (200) - **isOfType** (boolean) - True if the value is an array and all elements match the callback's type guard. ### Response Example ```json { "example": "true" } ``` ``` ```APIDOC ## isStringArray(value) ### Description Similar to `Array.isArray()` but also checks that the array only contains values of type `string` and sets the type to `string[]` rather than `any[]`. ### Parameters #### Path Parameters - **value** (any) - Required - The value to check. ### Response #### Success Response (200) - **isStringArray** (boolean) - True if the value is an array and all elements are strings. ### Response Example ```json { "example": "true" } ``` ``` ```APIDOC ## typesafeIsArray(value) ### Description Does the exact same thing as `Array.isArray()` but derives the type `unknown[]` rather than `any[]`, which improves strictness in a positive type narrowing scenario (`if (typesafeIsArray(value))`) but doesn't work as well for negative type narrowing (prefer `if (!Array.isArray(value))` then). ### Parameters #### Path Parameters - **value** (any) - Required - The value to check. ### Response #### Success Response (200) - **isArray** (boolean) - True if the value is an array. ### Response Example ```json { "example": "true" } ``` ``` ```APIDOC ## guardedArrayIncludes(collection, searchElement) ### Description Type-narrowing variant of `Array.prototype.includes` that works on arrays and sets. Returns `true` if `searchElement` is strictly equal to a member of `collection`. When `true`, narrows the type of `searchElement` to the element type of the iterable. ### Parameters #### Path Parameters - **collection** (Iterable) - Required - The array or set to search within. - **searchElement** (any) - Required - The element to search for. ### Request Example ```javascript /** @type {readonly ("red"|"green"|"blue")[]} */ const COLORS = ["red", "green", "blue"]; let input /** @type {string | number} */ = Math.random() > 0.5 ? 'red' : 42; if (guardedArrayIncludes(COLORS, input)) { // inside: input is now "red"|"green"|"blue" } ``` ### Response #### Success Response (200) - **includes** (boolean) - True if the `searchElement` is found in the `collection`. ### Response Example ```json { "example": "true" } ``` ``` ```APIDOC ## ensureArray(value) ### Description Converts a value to an array if it isn't already one. If `value` is already an array, returns it as-is. Otherwise, wraps `value` in a new single-element array. Useful for normalizing inputs that may be either a single item or an array of items. ### Parameters #### Path Parameters - **value** (any) - Required - The value to ensure is an array. ### Request Example ```javascript /** @type {string | string[]} */ const input = Math.random() > 0.5 ? 'single' : ['multiple', 'items']; const normalized = ensureArray(input); // always string[] ``` ### Response #### Success Response (200) - **arrayValue** (Array) - The value, ensured to be an array. ### Response Example ```json { "example": "['single']" } ``` ``` -------------------------------- ### Explain Variable Type Source: https://context7.com/voxpelli/typed-utils/llms.txt Provides a `typeof`-like explanation for a variable, with specific distinctions for `null` and `array` types. This helps in understanding the precise type of a variable at runtime. ```javascript import { explainVariable } from '@voxpelli/typed-utils'; console.log(explainVariable('hello')); // 'string' console.log(explainVariable(42)); // 'number' console.log(explainVariable(true)); // 'boolean' console.log(explainVariable(null)); // 'null' (not 'object') console.log(explainVariable([1, 2, 3])); // 'array' (not 'object') console.log(explainVariable({ a: 1 })); // 'object' console.log(explainVariable(undefined)); // 'undefined' console.log(explainVariable(() => {})); // 'function' ``` -------------------------------- ### Check if object has a specific key Source: https://context7.com/voxpelli/typed-utils/llms.txt Use `isObjectWithKey` to verify if an object contains a specific property. This is useful for safely accessing properties that might not exist. ```javascript import { isObjectWithKey } from '@voxpelli/typed-utils'; function getEmail(data) { if (isObjectWithKey(data, 'email')) { // data is Record<'email', unknown> return data.email; } return null; } console.log(getEmail({ email: 'test@example.com' })); // 'test@example.com' console.log(getEmail({ name: 'Alice' })); // null ``` -------------------------------- ### Retrieve wrapped values with getValueByPath Source: https://context7.com/voxpelli/typed-utils/llms.txt Returns an object containing the value at the specified path, or false/undefined if the path is invalid. ```javascript import { getValueByPath } from '@voxpelli/typed-utils'; const config = { database: { host: 'localhost', port: 5432, credentials: null } }; // Get value at path const result = getValueByPath(config, 'database.host'); if (result) { console.log(result.value); // 'localhost' } // Works with array paths const port = getValueByPath(config, ['database', 'port']); if (port) { console.log(port.value); // 5432 } // Returns undefined for missing path console.log(getValueByPath(config, 'database.user')); // undefined // Returns false for invalid path console.log(getValueByPath(config, 'database.credentials.user')); // false (credentials is null) ``` -------------------------------- ### omit Source: https://context7.com/voxpelli/typed-utils/llms.txt Creates a new object without the specified keys. Implements TypeScript's `Omit` utility type at runtime. ```APIDOC ## omit(obj, keys) ### Description Creates a new object without the specified keys. TypeScript's `Omit` utility type with actual runtime implementation. ### Parameters #### Arguments - **obj** (object) - The object to omit keys from. - **keys** (string[]) - An array of keys to omit from the object. ### Returns - (object) - A new object with the specified keys removed. ### Example ```javascript import { omit } from '@voxpelli/typed-utils'; const user = { id: 1, name: 'Alice', password: 'secret', email: 'alice@example.com' }; const publicUser = omit(user, ['password']); // Result: { id: 1, name: 'Alice', email: 'alice@example.com' } // Type: Omit const minimal = omit(user, ['password', 'email']); // Result: { id: 1, name: 'Alice' } ``` ``` -------------------------------- ### assertObjectWithKey Source: https://context7.com/voxpelli/typed-utils/llms.txt Asserts that the value is an object and contains the specified property. ```APIDOC ## assertObjectWithKey(obj, key) ### Description Asserts that the value is an object and contains the specified property. ### Method N/A (This is a utility function, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { assertObjectWithKey } from '@voxpelli/typed-utils'; function getUserName(data) { assertObjectWithKey(data, 'name'); // data is now Record<'name', unknown> return String(data.name); } console.log(getUserName({ name: 'Alice', age: 30 })); // 'Alice' // getUserName({ age: 30 }); // Throws: Expected key "name" to exist in object ``` ### Response #### Success Response (200) N/A (This function throws an error on failure and returns void on success) #### Response Example None ``` -------------------------------- ### Object Property Guards Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Type-safe wrappers for checking object property ownership. ```APIDOC ## hasOwn(obj, key) ### Description Safe wrapper around `Object.hasOwn(obj, key)` that narrows the key type to the intersection of keys for union types. ## hasOwnAll(obj, key) ### Description Variant of `hasOwn` that narrows the key type to the full union of all possible keys across union object members. ``` -------------------------------- ### Assertion Functions Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Functions to assert conditions and throw errors if they are not met. ```APIDOC ## assertStrictEqual(actual, expected, [message]) ### Description Asserts strict equality (`===`) between `actual` and `expected`. If values differ, throws a `TypeHelpersAssertionEqualityError` with `actual` / `expected` metadata. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **actual** (any) - Required - The value to check. - **expected** (any) - Required - The value to compare against. - **message** (string) - Optional - A custom error message. ## assertObjectWithKey(obj, key) ### Description Asserts that `obj` is an object and contains the property `key`. Throws an error if not. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to check. - **key** (string | number | symbol) - Required - The key to check for. ## assertType(value, type, [message]) ### Description Asserts that `value` is of the given `type` (string literal, eg. `'string'`, `'number'`, `'array'`, `'null'`). Supports union types by passing an array of type names. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **value** (any) - Required - The value to check. - **type** (string | string[]) - Required - The expected type or union of types. - **message** (string) - Optional - A custom error message. ## assertKeyWithType(obj, key, type) ### Description Asserts that `obj` is an object, contains the property `key`, and that `obj[key]` is of the given `type`. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to check. - **key** (string | number | symbol) - Required - The key to check. - **type** (string | string[]) - Required - The expected type or union of types for the key's value. ## assertKeyWithValue(obj, key, value) ### Description Asserts that `obj` is an object, contains the property `key`, and that `obj[key]` is strictly equal to the given `value`. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to check. - **key** (string | number | symbol) - Required - The key to check. - **value** (any) - Required - The expected value for the key. ## assertOptionalKeyWithType(obj, key, type) ### Description Asserts that `obj` is an object and either does not contain the property `key`, or if present, that `obj[key]` is `undefined` or of the given `type`. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to check. - **key** (string | number | symbol) - Required - The key to check. - **type** (string | string[]) - Required - The expected type or union of types for the key's value. ## assertArrayOfLiteralType(value, type, [message]) ### Description Asserts that `value` is an array where every element is of the given `type` (string literal, eg. `'string'`, `'number'`, `'array'`, `'null'`). Supports union types by passing an array of type names. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **value** (Array) - Required - The array to check. - **type** (string | string[]) - Required - The expected type or union of types for array elements. - **message** (string) - Optional - A custom error message. ## assertObjectValueType(obj, type) ### Description Asserts that `obj` is an object where all values are of the given `type` and all keys are strings. Useful for validating objects used as dictionaries/maps. ### Method ASSERT ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters - **obj** (object) - Required - The object to check. - **type** (string | string[]) - Required - The expected type or union of types for object values. ``` -------------------------------- ### Array Utilities Source: https://context7.com/voxpelli/typed-utils/llms.txt Functions for filtering arrays and performing type-safe array checks. ```APIDOC ## filter(inputArray, [valueToRemove]) ### Description Creates a new array with all values from the input array except those matching the value to remove. The returned array type excludes the removed value type. ### Parameters #### Arguments - **inputArray** (Array) - Required - The array to filter. - **valueToRemove** (any) - Optional - The value to remove from the array (defaults to undefined). ### Response - **Result** (Array) - A new array with the specified values removed, with a narrowed type. ## filterWithCallback(value, callback) ### Description Filters an array using a type guard callback function with an 'is' type predicate to ensure the returned array has the correctly narrowed type. ### Parameters #### Arguments - **value** (Array) - Required - The array to filter. - **callback** (Function) - Required - A type guard function that returns a boolean. ## isArrayOfType(value, callback) ### Description Checks if a value is an array where all elements pass the provided type guard callback. ### Parameters #### Arguments - **value** (any) - Required - The value to check. - **callback** (Function) - Required - A type guard function. ## isStringArray(value) ### Description Checks if a value is an array containing only strings, narrowing the type to string[]. ### Parameters #### Arguments - **value** (any) - Required - The value to check. ## typesafeIsArray(value) ### Description Performs an array check similar to Array.isArray() but derives the type unknown[] instead of any[]. ### Parameters #### Arguments - **value** (any) - Required - The value to check. ``` -------------------------------- ### isPropertyKey Source: https://context7.com/voxpelli/typed-utils/llms.txt Checks if a value is a valid `PropertyKey` (string, number, or symbol). ```APIDOC ## isPropertyKey(value) ### Description Returns true when value is a valid `PropertyKey` (`string | number | symbol`). ### Parameters #### Arguments - **value** (any) - The value to check. ### Returns - (boolean) - True if the value is a string, number, or symbol, false otherwise. ### Example ```javascript import { isPropertyKey } from '@voxpelli/typed-utils'; function safeAccess(obj, key) { if (isPropertyKey(key)) { return obj[key]; } return undefined; } const data = { a: 1, b: 2 }; console.log(safeAccess(data, 'a')); // 1 console.log(safeAccess(data, Symbol.for('x'))); // undefined (but valid key) console.log(safeAccess(data, {})); // undefined (invalid key) ``` ``` -------------------------------- ### Runtime Assertion Helper Source: https://context7.com/voxpelli/typed-utils/llms.txt The `assert` function throws a `TypeHelpersAssertionError` if a given condition is falsy. It's used internally by other assertion helpers and can be used directly for custom runtime checks. ```javascript import { assert } from '@voxpelli/typed-utils'; function divide(a, b) { assert(b !== 0, 'Division by zero is not allowed'); return a / b; } console.log(divide(10, 2)); // 5 // divide(10, 0); // Throws: TypeHelpersAssertionError: Division by zero is not allowed ``` -------------------------------- ### isKeyWithType Source: https://context7.com/voxpelli/typed-utils/llms.txt Checks if an object has a key and if its value is of a specific type. ```APIDOC ## isKeyWithType(obj, key, type) ### Description Returns true if the object contains the property and the property value is of the given type. ### Parameters #### Arguments - **obj** (object) - The object to check. - **key** (string | number | symbol) - The key of the property to check. - **type** (string) - The expected type of the property's value. ### Returns - (boolean) - True if the object has the key and its value is of the specified type, false otherwise. ### Example ```javascript import { isKeyWithType } from '@voxpelli/typed-utils'; function processData(data) { if (isKeyWithType(data, 'count', 'number')) { // data.count is number return data.count * 2; } return 0; } console.log(processData({ count: 5 })); // 10 console.log(processData({ count: 'five' })); // 0 console.log(processData({})); // 0 ``` ``` -------------------------------- ### Check type with union support Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Returns true if the value matches the provided type or union of types. ```javascript if (isType(value, ['string', 'number'])) { // value is narrowed to string | number } ``` -------------------------------- ### isKeyWithValue Source: https://context7.com/voxpelli/typed-utils/llms.txt Checks if an object has a key and if its value strictly equals a given value. ```APIDOC ## isKeyWithValue(obj, key, value) ### Description Returns true if the object contains the property and the property value is strictly equal to the given value. ### Parameters #### Arguments - **obj** (object) - The object to check. - **key** (string | number | symbol) - The key of the property to check. - **value** (any) - The value to compare against. ### Returns - (boolean) - True if the object has the key and its value is strictly equal to the given value, false otherwise. ### Example ```javascript import { isKeyWithValue } from '@voxpelli/typed-utils'; function isErrorResponse(response) { return isKeyWithValue(response, 'status', 'error'); } function handleResponse(response) { if (isKeyWithValue(response, 'type', 'user')) { // response.type is 'user' return `User: ${response.name}`; } if (isKeyWithValue(response, 'type', 'group')) { // response.type is 'group' return `Group: ${response.name}`; } return 'Unknown'; } console.log(handleResponse({ type: 'user', name: 'Alice' })); // 'User: Alice' ``` ``` -------------------------------- ### Strict Equality Assertion Source: https://context7.com/voxpelli/typed-utils/llms.txt Use `assertStrictEqual` to verify strict equality (`===`) between two values. If they differ, it throws a `TypeHelpersAssertionEqualityError` containing diff information. ```javascript import { assertStrictEqual } from '@voxpelli/typed-utils'; function validateResponse(response) { assertStrictEqual(response.status, 200, 'Expected successful response'); assertStrictEqual(response.ok, true); return response.data; } // Success case validateResponse({ status: 200, ok: true, data: { id: 1 } }); // Failure case - throws with diff info // validateResponse({ status: 404, ok: false, data: null }); // Throws: TypeHelpersAssertionEqualityError with actual=404, expected=200 ``` -------------------------------- ### Perform safe property checks with hasOwn Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Use this to narrow keys in union types while excluding prototype chain properties. ```javascript const shape = Math.random() > 0.5 ? { kind: 'a', value: 1 } : { kind: 'b', label: 'hi' }; let k /** @type {string | number | symbol} */ = 'kind'; if (hasOwn(shape, k)) { // k narrowed to 'kind' console.log(shape[k]); // 'a' | 'b' (further narrowed by shape.kind checks) } ``` -------------------------------- ### Assert Object Has Key Source: https://context7.com/voxpelli/typed-utils/llms.txt Use to ensure an object has a specific key. The value associated with the key is then typed as 'unknown'. ```javascript import { assertObjectWithKey } from '@voxpelli/typed-utils'; function getUserName(data) { assertObjectWithKey(data, 'name'); // data is now Record<'name', unknown> return String(data.name); } console.log(getUserName({ name: 'Alice', age: 30 })); // 'Alice' // getUserName({ age: 30 }); // Throws: Expected key "name" to exist in object ``` -------------------------------- ### Check object ownership with hasOwn Source: https://context7.com/voxpelli/typed-utils/llms.txt A type-safe wrapper around Object.hasOwn() that excludes prototype properties and narrows key types. ```javascript import { hasOwn } from '@voxpelli/typed-utils'; const config = { host: 'localhost', port: 3000 }; let key = 'host'; if (hasOwn(config, key)) { // key is narrowed to 'host' | 'port' console.log(config[key]); // 'localhost' } // Safe against prototype pollution const obj = { a: 1 }; console.log(hasOwn(obj, 'toString')); // false (prototype method) console.log(hasOwn(obj, 'a')); // true ``` -------------------------------- ### assertStrictEqual(actual, expected, [message]) Source: https://context7.com/voxpelli/typed-utils/llms.txt Asserts strict equality between two values, throwing a TypeHelpersAssertionEqualityError on failure. ```APIDOC ## assertStrictEqual(actual, expected, [message]) ### Description Asserts strict equality (`===`) between actual and expected values. Throws `TypeHelpersAssertionEqualityError` with diff metadata if values differ. ### Parameters - **actual** (any) - Required - The value to test. - **expected** (any) - Required - The value to compare against. - **message** (string) - Optional - Custom error message. ``` -------------------------------- ### isObjectWithKey Source: https://context7.com/voxpelli/typed-utils/llms.txt Checks if a value is an object containing a specific key. ```APIDOC ## isObjectWithKey(obj, key) ### Description Returns true if the value is an object containing the specified property. ### Parameters #### Arguments - **obj** (object) - The object to check. - **key** (string | number | symbol) - The key to look for in the object. ### Returns - (boolean) - True if the object contains the key, false otherwise. ### Example ```javascript import { isObjectWithKey } from '@voxpelli/typed-utils'; function getEmail(data) { if (isObjectWithKey(data, 'email')) { // data is Record<'email', unknown> return data.email; } return null; } console.log(getEmail({ email: 'test@example.com' })); // 'test@example.com' console.log(getEmail({ name: 'Alice' })); // null ``` ``` -------------------------------- ### Object Path Accessors Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Utilities for accessing values within nested object structures using string or array paths. ```APIDOC ## getObjectValueByPath(obj, path, createIfMissing) ### Description Returns the object at the specified path. Optionally creates missing objects if `createIfMissing` is true. ## getStringValueByPath(obj, path) ### Description Returns the string value at the specified path, or false if not a string. ## getValueByPath(obj, path) ### Description Returns an object containing the value at the specified path. ``` -------------------------------- ### assertObject(obj) Source: https://context7.com/voxpelli/typed-utils/llms.txt Asserts that a value is a non-null, non-array object. ```APIDOC ## assertObject(obj) ### Description Asserts that the value is a non-null, non-array object. Narrows type to `Record` for indexed property access. ### Parameters - **obj** (any) - Required - The value to validate as an object. ``` -------------------------------- ### looksLikeAnErrnoException Source: https://context7.com/voxpelli/typed-utils/llms.txt Checks if an error object resembles a Node.js `ErrnoException` by verifying the presence of `code` and `path` properties. ```APIDOC ## looksLikeAnErrnoException(err) ### Description Returns true if the error looks like a Node.js `ErrnoException` (has `code` and `path` properties). ### Parameters #### Path Parameters - **err** (Error) - Required - The error object to check. ### Request Example ```javascript import { looksLikeAnErrnoException } from '@voxpelli/typed-utils'; import { readFileSync } from 'fs'; try { readFileSync('/nonexistent/file.txt'); } catch (err) { if (looksLikeAnErrnoException(err)) { console.log(`Error code: ${err.code}`); console.log(`File path: ${err.path}`); } } ``` ``` -------------------------------- ### Check object type with narrowing Source: https://github.com/voxpelli/typed-utils/blob/main/README.md Checks if a value is a non-null, non-array object and narrows it to Record. ```javascript if (isObject(value)) { // value is Record — can do value['key'] } ```