Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created November 26, 2020 17: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 ycmjason/275069e762680c69dba6a843ee73342b to your computer and use it in GitHub Desktop.
Save ycmjason/275069e762680c69dba6a843ee73342b to your computer and use it in GitHub Desktop.
removeKeyRecursive.ts
type OmitRecursive<T extends object, O extends string> = Omit<
{ [K in keyof T]: T[K] extends object ? OmitRecursive<T[K], O> : T[K] },
O
>
const removeKeysRecursive = <T extends object, K extends readonly string[]>(
object: T,
keys: K,
): OmitRecursive<T, K[number]> => {
const KEYS_TO_BE_REMOVED = new Set(keys)
return Object.fromEntries(
Object.entries(object)
.filter(([key]) => !KEYS_TO_BE_REMOVED.has(key))
.map(([key, value]) => [
key,
typeof value === 'object' && value !== null ? removeKeysRecursive(value, keys) : value,
]),
) as any
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment