使用Typescript对对象方法进行动态属性访问



我正在使用flow来加快TypeScript的速度,我有一个小难题…

const methods: Array<keyof typeof console> = ["log", "error"];
beforeEach(() => {
methods.forEach((m) => jest.spyOn(console, m).mockImplementation(() => {}));
});

我希望这将工作,但我得到这个错误:

error TS2769: No overload matches this call.
Overload 1 of 4, '(object: Console, method: FunctionPropertyNames<Required<Console>>): SpyInstance<any, unknown[]>', gave the following error.
Argument of type 'keyof Console' is not assignable to parameter of type 'FunctionPropertyNames<Required<Console>>'.
Type '"Console"' is not assignable to type 'FunctionPropertyNames<Required<Console>>'.
Overload 2 of 4, '(object: Console, method: ConstructorPropertyNames<Required<Console>>): SpyInstance<any, unknown[]>', gave the following error.
Argument of type 'keyof Console' is not assignable to parameter of type 'ConstructorPropertyNames<Required<Console>>'.
Type '"error"' is not assignable to type 'ConstructorPropertyNames<Required<Console>>'.
22     methods.forEach((m) => jest.spyOn(console, m).mockImplementation(() => {}));

所以…缺失的是什么?

您没有给methods正确的类型。类型应为从console中提取的所有函数属性名。

type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T] & string;
const methods: FunctionPropertyNames<typeof console>[] = ['log', 'error'];
describe('69231740', () => {
beforeEach(() => {
methods.forEach((m) => jest.spyOn(console, m).mockImplementation());
});
});

包版本:

"@types/jest": "^26.0.18",
"jest": "^26.6.3",
"typescript": "^4.1.2"

相关内容

  • 没有找到相关文章

最新更新