The following is a simple typescript safe function which returns a clone of a supplied object with an arbitrary number of properties removed:
function removePropertiesFromObject<T, K extends keyof T>(obj: T, ...properties: K[]) {
const result = { ...obj };
for (const prop of properties) {
delete result[prop];
}
return result as Omit<T, K>;
}
Usage:
const original = { a: 1, b: 2, c: 3 };
const clone = removePropertiesFromObject(original, "a", "b");
console.log(clone); // { c: 3 }
Explanation:
The function has an object parameter (of type T) and a rest parameter for the properties to be removed (each of type K which is restricted to be a key of type T). When multiple properties are passed then K will be the union type of the properties provided. In the example above K will be of type "a" | "b".
The function then first clones the original object and subsequently removes the properties provided. This clone is still of type T though, so a cast is applied to re-align the type with the created object. In the example above this would lead to Omit<T, "a" | "b"> leaving "c" as the only resulting property of the return type.