TypeScript:给 window 对象分配自定义属性

28 浏览
0 Comments

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日
0
0 Comments

你可以通过声明合并来扩展Window的定义。

这不会产生错误:

interface Window {
  extensionName: {
    method1: () => {}
  }
}
window.extensionName.method1 = () => {
  return {};
}

TypeScript Playground演示了这种技术。

0
0 Comments

你可以使用 declare var 来声明 extensionName 存在于 globalThis 上 (文档)。

declare var extensionName: { method1: () => {} };
window.extensionName.method1 = () => {
  return {};
}

演示

0