Skip to content

isRecord function ​

Checks whether a value is a plain object: an object literal or Object.create(null). Arrays, class instances, dates and maps are excluded.

ts
import { isRecord } from 'utils';

Signature ​

ts
export function isRecord(value: unknown): value is Record<string, unknown>

Parameters ​

NameDescription
valueThe value to check.

Returns ​

true for a plain object.

Example ​

ts
isRecord({ a: 1 }); // true
isRecord([]); // false
isRecord(new Date()); // false

Tests ​

Line coverage: 100 %.

  • ✅ checks {} as true
  • ✅ checks {"a":1} as true
  • ✅ checks {} as true
  • ✅ checks [] as false
  • ✅ checks {"x":0} as false
  • ✅ checks {} as false
  • ✅ checks null as false
  • ✅ checks 1 as false

Source ​

src/guard/is-record.ts (on GitHub)

Used by ​

  • deepMerge: Applies a partial patch to nested settings, such as saved preferences over the defaults: plain objects are merged at every depth, other values replace, undefined keeps.
Source code
ts
/**
 * Checks whether a value is a plain object: an object literal or `Object.create(null)`. Arrays, class
 * instances, dates and maps are excluded.
 *
 * @param value - The value to check.
 * @returns `true` for a plain object.
 * @example
 * isRecord({ a: 1 }); // true
 * isRecord([]); // false
 * isRecord(new Date()); // false
 */
export function isRecord(value: unknown): value is Record<string, unknown> {
  if (typeof value !== 'object' || value === null) {
    return false;
  }
  const prototype: unknown = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}
Test file
ts
import { isRecord } from './is-record';

class Point {
  public readonly x = 0;
}

// Plain function type: calls are not seen as conditions, so any value can be passed.

describe(isRecord, () => {
  it.for([
    [{}, true],
    [{ a: 1 }, true],
    [Object.create(null), true],
    [[], false],
    [new Point(), false],
    [new Map(), false],
    [null, false],
    [1, false],
  ] as const)('checks %j as %s', ([value, expected]) => {
    expect(isRecord(value)).toBe(expected);
  });
});

Keywords: is, record, guards, function

Generated from the JSDoc of the sources.