如何在typescript中编写通用的omit函数?

q8l4jmvw  于 2023-05-23  发布在  TypeScript
关注(0)|答案(3)|浏览(135)
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>)
}

我想省略obj中的几个属性

brtdzjyr

brtdzjyr1#

不需要泛型函数,只需写例如:

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

filtered将包含sourceomit1omit2之外的所有属性。
如果你有字符串数组的键,你可以使用这样的方法:

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
}
envsm3lx

envsm3lx2#

可以使用Object.entriesObject.fromEntries过滤掉对象的属性。它也会使打字变得不那么麻烦。你只需要对最终结果进行强制转换:

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链接

9lowa7mx

9lowa7mx3#

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

相关问题