omit
Returns a new object without the specified keys.
1/**
2 * Returns a new object without the specified keys.
3 *
4 * @param obj - The source object.
5 * @param keys - An array of keys to omit from the object.
6 * @returns A new object without the omitted keys.
7 */
8export function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {
9 const result = {} as Omit<T, K>;
10 for (const key in obj) {
11 if (!keys.includes(key as K)) {
12 result[key as Exclude<keyof T, K>] = obj[key];
13 }
14 }
15 return result;
16}
Selective Exclusion of Properties
Allows precise removal of unwanted keys from an object, resulting in cleaner and more focused outputs.
Type-Safe with Accurate Output Shape
Leverages TypeScript’s
Omit
utility to ensure the return type excludes the specified keys at compile time.Immutable by Design
Constructs a new object without mutating the original input, promoting safe and predictable behavior.
Compatible with Arbitrary Key Sets
Accepts dynamic arrays of keys, making it versatile for runtime-based filtering.
Tests | Examples
1test('omit - removes specified keys from object', () => {
2 const obj = { a: 1, b: 2, c: 3 };
3 expect(omit(obj, ['b'])).toEqual({ a: 1, c: 3 });
4});
5
6test('omit - removes multiple keys', () => {
7 const obj = { a: 1, b: 2, c: 3 };
8 expect(omit(obj, ['a', 'c'])).toEqual({ b: 2 });
9});
10
11test('omit - returns original object if no keys match', () => {
12 const obj = { a: 1, b: 2 };
13 expect(omit(obj, ['x' as any, 'y' as any])).toEqual(obj);
14});
15
16test('omit - returns empty object if all keys removed', () => {
17 const obj = { a: 1 };
18 expect(omit(obj, ['a'])).toEqual({});
19});
20
21test('omit - works with empty object', () => {
22 expect(omit({}, ['a'])).toEqual({});
23});
24
25test('omit - works with empty keys array', () => {
26 const obj = { a: 1, b: 2 };
27 expect(omit(obj, [])).toEqual({ a: 1, b: 2 });
28});
Common Use Cases
Sanitizing Sensitive Data
Remove private fields (e.g., passwords, tokens) before logging, storing, or sending data over the network.
Form or UI Cleanup
Strip internal or metadata fields before displaying or submitting form data.
API Request Shaping
Exclude client-only or temporary fields when preparing payloads for backend requests.
Simplifying Props
Pass only relevant props to components by omitting extra or internal ones.
Debugging or Logging
Log only safe fields from complex objects by omitting verbose or irrelevant data.