Skip to content

Utils

assert

Asserts that a value is truthy, throwing an error if it’s falsy. This is a TypeScript type assertion function that helps with type narrowing.

noop

No-operation function that accepts any parameters and returns undefined. Useful as a default callback or for stubbing functionality.

identity

Identity function that returns the first argument unchanged. Can accept additional parameters but ignores them.

sleep

Creates a promise that resolves after the specified number of milliseconds. Useful for creating delays in async functions.

isObject

Type guard that checks if a value is an object (non-null and typeof ‘object’). Provides advanced type narrowing to either the original object type or a generic object type.

isRec

Type guard that checks if a value is a plain object (a simple object literal or created with Object.create(null)). Verifies that the object either has no prototype or its prototype is Object.prototype.

isShallowEqual

Performs a shallow equality comparison between two values. Handles primitives, objects, dates, regular expressions, arrays, maps, and sets.

For iterables, compares each item in sequence for equality. For objects, compares direct property values but not nested objects deeply.

isDeepEqual

Performs a deep equality comparison between two values. Recursively compares nested objects and arrays while properly handling cyclic references.

Handles primitives, objects, dates, regular expressions, arrays, maps, and sets. Uses a WeakMap to track visited objects to avoid infinite recursion with circular references.

assign

Type-safe version of Object.assign that properly handles type merging. Unlike standard Object.assign typing, properties with the same name are replaced rather than becoming a union type.

merge

Creates a new object with merged properties from all provided objects. Similar to Object.assign but always creates a new object rather than mutating the first argument.

Example

// Creates a new object: { a: 1, b: 2, c: 3 }
const obj = merge({ a: 1 }, { b: 2 }, { c: 3 })

keys

Type-safe version of Object.keys that preserves the key type information. Returns an array of keys with the correct type for the object.

entries

Type-safe version of Object.entries that preserves key and value type information. Returns an array of key-value pairs with correct types.

fromEntries

Type-safe version of Object.fromEntries that preserves key and value type information. Creates an object from an iterable of key-value pairs.

pick

Creates a new object with only the specified keys from the original object.

Example

const user = { id: 1, name: 'Alice', email: 'alice@example.com' }
const userInfo = pick(user, ['name', 'email'])
// Result: { name: 'Alice', email: 'alice@example.com' }

omit

Creates a new object excluding the specified keys from the original object.

Example

const user = { id: 1, name: 'Alice', password: 'secret' }
const safeUser = omit(user, ['password'])
// Result: { id: 1, name: 'Alice' }

jsonClone

Creates a deep clone of a value using JSON serialization/deserialization. This is a type-safe shortcut to JSON.parse(JSON.stringify(value)).

Note: This has limitations with circular references, functions, symbols, and special objects like Date (converts to string). Consider using the native structuredClone when available.

random

Generates a random integer between min and max (inclusive).

mockRandom

Replaces the default random number generator with a custom implementation. Useful for testing to provide deterministic “random” values.

Example

// Set up deterministic random values for testing
const restore = mockRandom(() => 42)
console.log(random()) // Always returns 42
restore() // Back to normal random behavior

nonNullable

Asserts that a value is not null or undefined. Throws a TypeError if the value is null or undefined. Also serves as a type guard to narrow the type to non-nullable.

Example

const name = nonNullable(user.name) // TypeScript knows name is not null or undefined

toStringKey

Converts any JavaScript value to a stable string representation. Handles complex data structures and edge cases that JSON.stringify cannot manage.

Provides special handling for:

  • Circular references

  • Maps and Sets

  • Symbols

  • Functions

  • Custom class instances

  • Regular objects (with sorted keys for stability)

Example

// Handles circular references
const obj = { name: 'test' }
obj.self = obj
const key = toStringKey(obj) // No infinite recursion!
// Stable representation of objects (key order doesn't matter)
toStringKey({ a: 1, b: 2 }) === toStringKey({ b: 2, a: 1 }) // true

toAbortError

Converts any value to an AbortError. If the value is already an AbortError, it will be returned as is. Otherwise, creates a new AbortError with appropriate information.

Handles different environments by using DOMException when available or falling back to regular Error with name set to ‘AbortError’.

throwIfAborted

Checks if an AbortController is aborted and throws an AbortError if it is. Useful for quick abort checks at the beginning of async operations.

isAbort

Type guard that checks if a value is an AbortError.

throwAbort

Creates and throws an AbortError with the provided message. Optionally aborts the provided controller with the same error.

setTimeout

Enhanced version of the global setTimeout function. Ensures consistent behavior across different environments by handling both numeric and object timeout IDs. Adds a toJSON method to object timeout IDs for serialization.

MAX_SAFE_TIMEOUT

Maximum safe integer value for setTimeout delay. Any timeout value larger than this may cause overflow issues in some browsers.

isBrowser

Detects whether the code is running in a browser environment. Checks for the existence of window and document objects.

withResolvers

Creates a Promise and returns it along with its resolve and reject functions. This utility is similar to the upcoming Promise.withResolvers() static method. It allows for manual control over a Promise’s settlement from outside its constructor.

Example

const { promise, resolve, reject } = withResolvers<string>()
promise
.then((value) => console.log('Resolved:', value))
.catch((error) => console.error('Rejected:', error))
// Sometime later, or in a different part of the code:
if (Math.random() > 0.5) {
resolve('Success!')
} else {
reject(new Error('Failed!'))
}

removeItem

Removes the first occurrence of an item from an array in a single iteration. Mutates the array in place by splicing out the found element.

More efficient than using indexOf + splice as it only walks the array once.

Example

const items = [1, 2, 3, 4]
removeItem(items, 3) // returns true, items is now [1, 2, 4]
removeItem(items, 5) // returns false, items unchanged