React Typescript,从外部脚本调用函数

Ami*_*avi 3 javascript dom typescript react-tsx global-functions

在我的 React 应用程序中,我从服务器获取自定义 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)
}
Run Code Online (Sandbox Code Playgroud)

但这里我得到编译器错误

类型“Window”上不存在属性“manipulator”。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);
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

Obl*_*sys 5

您可以将其Window从 TypeScript 模块(ts 或 tsx)内部添加到界面,如下所示:

declare global {
  interface Window {
    manipulator: () => void;
  }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以创建一个全局变量global.d.ts(名称并不重要,只要它位于源目录中即可),其中包含以下内容:

declare interface Window {
  manipulator: () => void;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这使得该函数在任何地方都可用,甚至在脚本初始化之前也是如此。