TypeScript:给 window 对象分配自定义属性
TypeScript:给 window 对象分配自定义属性
这个问题已经在这里有了答案:
我有一个Web扩展,将一个自定义对象应用于window对象,如下所示:
window.extensionName // { method1: () => {} }
但是在我的TypeScript文件中,当我引用window.extensionName
时,我会收到以下错误:
Property 'extensionName' does not exist on type 'Window & typeof globalThis'.
但是它确实存在于window
对象中,因为它是由该扩展添加的。如何使TypeScript停止抱怨这个问题?
并且是否有一种全局指定新对象类型的方法,以便TypeScript可以使用自动完成?
admin 更改状态以发布 2023年5月23日
你可以通过声明合并来扩展Window
的定义。
这不会产生错误:
interface Window { extensionName: { method1: () => {} } } window.extensionName.method1 = () => { return {}; }
TypeScript Playground演示了这种技术。