Skip to content

omit function ​

Copies an object without some of its properties, without delete, which slows down V8.

ts
import { omit } from 'utils';

Signature ​

ts
export function omit<T extends object, K extends keyof T>(object: T, keys: readonly K[]): Omit<T, K>

Parameters ​

NameDescription
TThe type of the object.
KThe keys to leave out.
objectThe source object.
keysThe keys to leave out.

Returns ​

A new object with the other properties.

Example ​

ts
omit({ id: 1, name: 'Pump', internalRef: 'x' }, ['internalRef']); // { id: 1, name: 'Pump' }

Tests ​

Line coverage: 100 %.

  • ✅ leaves the requested keys out
  • ✅ keeps symbol keys and does not modify the source
  • ✅ skips non-enumerable properties

Source ​

src/object/omit.ts (on GitHub)

Source code
ts
/**
 * Copies an object without some of its properties, without `delete`, which slows down V8.
 *
 * @template T - The type of the object.
 * @template K - The keys to leave out.
 * @param object - The source object.
 * @param keys - The keys to leave out.
 * @returns A new object with the other properties.
 * @example
 * omit({ id: 1, name: 'Pump', internalRef: 'x' }, ['internalRef']); // { id: 1, name: 'Pump' }
 */
export function omit<T extends object, K extends keyof T>(object: T, keys: readonly K[]): Omit<T, K> {
  const excluded = new Set<PropertyKey>(keys);
  const result: Record<PropertyKey, unknown> = {};
  for (const key of Reflect.ownKeys(object)) {
    if (!excluded.has(key) && Object.prototype.propertyIsEnumerable.call(object, key)) {
      result[key] = Reflect.get(object, key);
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- Every other own enumerable key is copied.
  return result as Omit<T, K>;
}
Test file
ts
import { omit } from './omit';

describe(omit, () => {
  it('leaves the requested keys out', () => {
    expect(omit({ id: 1, name: 'Pump', internalRef: 'x' }, ['internalRef'])).toStrictEqual({ id: 1, name: 'Pump' });
  });

  it('keeps symbol keys and does not modify the source', () => {
    const tag = Symbol('tag');
    const source = { id: 1, [tag]: 'kept' };
    expect(omit(source, ['id'])).toStrictEqual({ [tag]: 'kept' });
    expect(source).toStrictEqual({ id: 1, [tag]: 'kept' });
  });

  it('skips non-enumerable properties', () => {
    const source = Object.defineProperty({ id: 1 }, 'hidden', { value: true, enumerable: false });
    expect(omit(source, [])).toStrictEqual({ id: 1 });
  });
});

Keywords: omit, objects, function

Generated from the JSDoc of the sources.