0

Having a fresh new project in React and Typescript, I need to use a JS Lib developed by my fellow colleagues.

The lib is packaged and added to the project with NPM. The content of the min.js is like:

window.SharedObj=function(e){
...
}

So, this lib is designed to register an instance of SharedObj at the window scope, and I need to retrieve this instance in my top level component (index.tsx).

I've successufully done it this way:

require('path/lib.min.js');

// @ts-ignore
new SharedObj();

if ((window as any).SharedObj) {
    ReactDOM.render(
        <React.StrictMode>
            <App/>
        </React.StrictMode>,
        document.getElementById('root')
    );
}

This works, but it seems wrong to me to ts-ignore and "as any" in order to make this work.

Do you have a better solution ? May I extend the Window definition ?

0

1 Answer 1

3

You can declare the Window object globally as an interface with SharedObj being one of it's property.

declare global {
  interface Window {
    // you'll need to explicitly specify the
    // type of arguments & function return type
    SharedObj: (e: ArgsType) => ReturnType;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.