TypeScript动态访问对象方法触发TS2769错误如何解决?
报错原因
你声明的Array<keyof typeof console>类型覆盖了Console接口的所有属性,包括非函数类型的属性(比如构造函数标识、静态属性等),而jest.spyOn仅支持接收函数类型的属性名作为第二个参数,因此出现类型不匹配的报错。
解决方案
- 方案1(最推荐,适合固定mock指定方法的场景)
使用as const断言缩小数组类型范围,TS会将methods推导为精确的字面量联合类型,和jest.spyOn要求的入参类型完全匹配:
const methods = ["log", "error"] as const; beforeEach(() => { methods.forEach((m) => jest.spyOn(console, m).mockImplementation(() => {})); });
- 方案2(适合需要动态筛选所有函数属性的场景)
自定义工具类型筛选出Console对象上所有值为函数的属性名,再限定methods的元素类型:
// 提取对象中所有值为函数的属性名 type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T] const methods: Array<FunctionPropertyNames<typeof console>> = ["log", "error"]; beforeEach(() => { methods.forEach((m) => jest.spyOn(console, m).mockImplementation(() => {})); });
- 方案3(临时兼容方案,不推荐长期使用)
使用类型断言绕过类型校验,适合快速验证逻辑时使用:
const methods: Array<keyof typeof console> = ["log", "error"]; beforeEach(() => { methods.forEach((m) => jest.spyOn(console, m as FunctionPropertyNames<Required<Console>>).mockImplementation(() => {})); });
内容的提问来源于stack exchange,提问作者Andrew Smith
相关产品推荐
相关产品推荐

