Search code examples
javascripttypescriptdomreact-tsxglobal-functions

React Typescript, Call a function from external script


In my react application, I fetch a custom javascript file from the server and append it as a script tag to the body of document.

this newly added custom file contains a method called manipulator. Now in one of the components, I want to call that function. As I know the function should exist in the window global object.

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)
}

But here I get the compiler error

Property 'manipulator' does not exist on type 'Window'.ts(2339)

which is totally logical, but I did not find a way to create an extended interface for window or any other way to tell the compiler that there is an optional function in window called manipulator.

Any help is appreciated.

  ----------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);
      });
    });
  }

Solution

  • You can add it to the Window interface from inside a TypeScript module (ts or tsx) like this:

    declare global {
      interface Window {
        manipulator: () => void;
      }
    }
    

    Or you can create a global global.d.ts (name doesn't matter, only that it's inside your source directory), containing this:

    declare interface Window {
      manipulator: () => void;
    }
    

    Be aware that this makes the function available everywhere, also before the script is initialized.