在我的反应应用程序中,我从服务器获取一个自定义的javascript文件,并将其作为script
标记附加到document
的主体。
这个新添加的自定义文件包含一个名为manipulator
的方法。现在在其中一个组件中,我想调用该函数。据我所知,该函数应该存在于window
全局对象中。
if(documnet.getElementById('customJsId')){ // check if the script tag exists in document
window.manipulator(); // which I get Property 'iframeManipulator' does not exist on type 'Window'.ts(2339)
}
但在这里我得到了编译器错误
属性'操纵者'在'Window'上不存在.ts(2339)
这是完全合乎逻辑的,但我找不到为window
创建扩展接口的方法或任何其他方式告诉编译器在window
中有一个名为manipulator
的可选函数。
任何帮助表示赞赏。
----------Just in case--how the script is added to document--------------
loadProjectCustomJS() {
runInAction(async () => {
thisfetchProjectJs().then((doc) => {
const body: HTMLBodyElement = document.getElementsByTagName('body')[0];
const customjs: HTMLScriptElement = document.createElement('script');
customjs.type = 'text/javascript';
customjs.id = 'customJsId'
customjs.src = doc.get('resourceUrl');
body.appendChild(customjs);
});
});
}
您可以从TypeScript模块(ts或tsx)中将它添加到Window
接口,如下所示:
declare global {
interface Window {
manipulator: () => void;
}
}
或者你可以创建一个全局global.d.ts
(名称无关紧要,只是它在你的源目录中),包含:
declare interface Window {
manipulator: () => void;
}
请注意,这使得函数在任何地方都可用,也在脚本初始化之前。