1.38.0omit
Creates a new object without the specified own enumerable properties.
omit(object, keys):Omit<T, K>How it works
The function first creates a shallow copy of the object using object spread syntax. It then deletes each key provided in the keys array from the copy.
Original object
The original object is not modified because the properties are deleted from a new shallow copy.
Shallow copy
Nested objects and arrays are not cloned. Their references are copied to the resulting object, so modifying a nested value through the result can also affect the original object.
Type-safe keys
The K generic is constrained to keyof T, so TypeScript restricts the keys array to keys that exist on the input object.
Parameters
objectTrequiredThe object from which properties should be omitted.
keysK[]requiredAn array of keys to remove from the resulting object.
Returns
Omit<T, K>A new object containing the properties of the original object except for the specified keys.
Examples
Basic usage
const user = {
name: "Amir",
age: 22,
role: "developer",
};
omit(user, ["age"]);
// {
// name: "Amir",
// role: "developer",
// }Omit multiple properties
const user = {
name: "Amir",
age: 22,
role: "developer",
};
omit(user, ["age", "role"]);
// {
// name: "Amir",
// }Empty keys
const user = {
name: "Amir",
age: 22,
};
omit(user, []);
// {
// name: "Amir",
// age: 22,
// }Omitting all properties
const user = {
name: "Amir",
age: 22,
};
omit(user, ["name", "age"]);
// {}Original object is unchanged
const user = {
name: "Amir",
age: 22,
};
const result = omit(user, ["age"]);
console.log(user);
// {
// name: "Amir",
// age: 22,
// }Nested objects are preserved
const user = {
name: "Amir",
profile: {
age: 22,
},
};
const result = omit(user, ["name"]);
result.profile.age = 25;
console.log(user.profile.age);
// 25Falsy values are preserved
const data = {
count: 0,
active: false,
name: "",
};
omit(data, ["active"]);
// {
// count: 0,
// name: "",
// }Undefined values
const data = {
value: undefined,
name: "Amir",
};
omit(data, ["name"]);
// {
// value: undefined,
// }