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

Dynamic property access of methods of an object with Typescript

我正在通过使用流来加快 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"