Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Created October 17, 2021 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/461026f981ac6ddd4dc2de82c57e3e9b to your computer and use it in GitHub Desktop.
Save Oaphi/461026f981ac6ddd4dc2de82c57e3e9b to your computer and use it in GitHub Desktop.
Utility types and helper for deeply omitting a field from an object
type DeepKeyof<T, A = never> = { [P in keyof T]: T[P] extends object ? P extends A ? P : DeepKeyof<T[P], A | keyof T> | P : P }[keyof T];
type DeepOmit<T, U extends DeepKeyof<T>> = {
[P in keyof T as P extends U ? never : P]: T[P] extends object ?
keyof DeepOmit<T[P], Extract<U, DeepKeyof<T[P]>>> extends never ?
{} :
DeepOmit<T[P], Extract<U, DeepKeyof<T[P]>>> :
T[P]
};
/**
* @summary deep omits a property from an object
* @param obj object to omit from
* @param key name of the property to omit
* @returns a copy of the object without the key
*/
const deepOmit = <T, U extends DeepKeyof<T>>(obj: T, key: U) => {
const filtered = {} as DeepOmit<T, U>;
Object.entries(obj).forEach(([k, v]) => {
if (k === key) return;
filtered[k as keyof DeepOmit<T, U>] = typeof v === "object" ?
deepOmit(v as T[keyof T], key as Extract<U, DeepKeyof<keyof T>>) :
v;
});
return filtered;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment