3

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);
      });
    });
  }
1
  • window[“manipulator”]() Commented Apr 28, 2019 at 17:31

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I chose declare global was suiting better for my case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.