Created
October 17, 2021 23:11
-
-
Save Oaphi/461026f981ac6ddd4dc2de82c57e3e9b to your computer and use it in GitHub Desktop.
Utility types and helper for deeply omitting a field from an object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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