简体   繁体   中英

Use window object from JS lib in React Typescript project

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM