我有一个类似omit功能的函数:
/**
* 从source处拷贝需要的字段
*
* @param source
* @param ignoreProps 不需要拷贝的字段
*/
export function omit<T extends Record<string, any>, K extends keyof T>(source: T, ignoreProps: K[]): Omit<T, K> {
if (!source) return source
return Object
.entries(source)
.reduce((obj, [key, value]) => {
!(ignoreProps as string[]).includes(key) && (obj[key] = value)
return obj
}, Object.create(null))
}
我现在想把ignoreProps
入参改为函数类型,即ignoreProps: () => K[]
,那我函数的返回类型该怎么写才能让说omit({a: 1, b: 2}, ()=>['a'])
能正确推导出{a: 1}
的结果类型?
就把参数
ignoreProps
改成ignoreFn: () => K[]
这样子了,下面的ignoreProps
用ignoreFn()
代替一下就好了。