如何解决window.opener相关的TypeScript类型报错问题
报错原因及解决方案
报错1:No overload matches this call(ts2769)
- 原因:TypeScript 内置类型中
window.opener的默认类型为Window | null,TS 无法感知到你已经通过Object.defineProperty手动给它赋值了非空值,因此检测到你可能把null传入了要求入参为非空对象的jest.spyOn方法,触发类型报错。 - 解决方案:使用非空断言操作符
!明确告知 TS 该值此时一定非空即可:
const spy = jest.spyOn(window.opener!, 'postMessage')
报错2:The operand of a 'delete' operator must be optional(ts2790)
- 原因:TypeScript 内置
Window接口里opener被定义为必选属性,语法层面不允许直接删除必选属性,因此触发报错。 - 解决方案:通过类型断言把
window临时转为可选属性集合或者any类型再执行删除操作即可:
// 方案1:更规范的Partial类型断言 delete (window as Partial<Window>).opener // 方案2:测试场景下简便写法 delete (window as any).opener
完整修改后代码
test('a test', () => { Object.defineProperty(window, 'opener', { value: mockMessage, configurable: true }) const spy = jest.spyOn(window.opener!, 'postMessage') delete (window as Partial<Window>).opener })
内容的提问来源于stack exchange,提问作者rottitime
相关产品推荐
相关产品推荐

