Typescript:添加外部依赖的实例到窗口对象



我正在将外部依赖项集成到企业项目中。集成是这样的:

window.foo = new Foo({
container: `#${iframeContainerId}`,
plugin: { id: pluginId },
})

Typescript不抱怨windows .foo

,因为我有这样的声明:

declare global {
interface Window {
foo: any
}
}
我得到错误Cannot find name 'Foo'

有没有办法让Typescript忽略这个?外部依赖是使用外部脚本加载的,我认为它不存在类型定义。

您可以使用如下类型声明您的Foo类:

declare class Foo {
constructor(obj: {
container: string,
plugin: { id: string },
});
// other methods here
}

最后我采用的解决方案是

declare global {
interface Window {
foo: any
Foo: any
}
}

对于积分

window.foo = new window.Foo({
container: `#${iframeContainerId}`,
plugin: { id: pluginId },
})

解决方案Ovidijus Parsiunas工作,但由于错误,我需要在项目中添加.babelrc文件,所以我使用了这个。

最新更新