[英]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.在 React 和 Typescript 中有一个全新的项目,我需要使用我的同事开发的 JS Lib。
The lib is packaged and added to the project with NPM.该 lib 被打包并添加到项目中,使用 NPM。 The content of the min.js is like:
min.js 的内容如下:
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).因此,此库旨在在 window scope 注册 SharedObj 的实例,我需要在我的顶级组件 (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.这行得通,但我认为 ts-ignore 和 "as any" 来完成这项工作似乎是错误的。
Do you have a better solution?你有更好的解决方案吗? May I extend the Window definition?
我可以扩展 Window 定义吗?
You can declare the Window object globally as an interface with SharedObj
being one of it's property.您可以将Window object 全局声明为接口,其中
SharedObj
是其属性之一。
declare global {
interface Window {
// you'll need to explicitly specify the
// type of arguments & function return type
SharedObj: (e: ArgsType) => ReturnType;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.