Home > OS >  How to write generic omit function in typescript?
How to write generic omit function in typescript?

Time:09-16

function omit<T, P extends keyof T>(obj: T, okeys: P[]) {
    return (Object.keys(obj) as Array<keyof T>).reduce((newObj, key)=> {
        for (const filKey of okeys) {
            if (filKey != key) {
                newObj[key] = obj[key];
            }
        }
        return newObj;
    }, {} as Omit<T,P>)
}

I want to omit the few properties from obj

CodePudding user response:

There is no need for a generic function, just write e.g.:

const { omit1, omit2, ...filtered } = source

filtered will contain all the properties of source except omit1 and omit2.

If you have the keys as array of string, you could go with something like this:

function omit<T extends object, P extends keyof T>(obj: T, okeys: P[]): Omit<T, P> {
  const ret = { ...obj }
  okeys.forEach((key) => delete ret[key])
  return ret
}

CodePudding user response:

You can use Object.entries and Object.fromEntries to filter out the properties of the object. It will make typing less cumbersome also. You will only need a cast for end result :

function omit2<T extends {}, P extends keyof T>(obj: T, okeys: P[]): Omit<T, P> {
  const b = Object.fromEntries(Object.entries(obj).filter(([k, _]) => !okeys.includes(k as P)))
  return b as Omit<T, P>;
}

Playground Link

  • Related