Window & 类型上不存在属性全局类型This [英] Property does not exist on type Window & typeof globalThis
问题描述
在 Electron-React-Typescript 应用程序中,我收到此错误:Property 'api' does not exist on type 'Window &类型的全局This'.window.api.send('open-type-A-window', '');
In a Electron-React-Typescript app I'm getting this error: Property 'api' does not exist on type 'Window & typeof globalThis'. window.api.send('open-type-A-window', '');
但是在 index.d.ts 文件中,我以这种方式声明了接口 Window:
But in a file index.d.ts I declared interface Window in this way:
declare global {
namespace NodeJS {
declare interface Window {
"electron": {
openNewWindow(): void;
},
"api": {
send: (channel, data) => {
ipcRenderer.invoke(channel, data).catch(e => console.log(e))
},
receive: (channel, func) => {
console.log("preload-receive called. args: ");
ipcRenderer.on(channel, (event, ...args) => func(...args));
},
electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => {
ipcRenderer.sendTo(window_id, channel, arg);
},
electronIpcSend: (channel: string, ...arg: any) => {
ipcRenderer.send(channel, arg);
},
electronIpcSendSync: (channel: string, ...arg: any) => {
return ipcRenderer.sendSync(channel, arg);
},
electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => {
ipcRenderer.on(channel, listener);
},
electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) =>
{
ipcRenderer.once(channel, listener);
},
electronIpcRemoveListener: (channel: string, listener: (event: any, ...arg: any)
=> void) => {
ipcRenderer.removeListener(channel, listener);
},
electronIpcRemoveAllListeners: (channel: string) => {
ipcRenderer.removeAllListeners(channel);
}
}
}
}
}
我已阅读此主题:https://github.com/Microsoft/TypeScript/问题/19816 但我没有得到正确的解决方案.
I've read this thread: https://github.com/Microsoft/TypeScript/issues/19816 but I didn't get the proper solution.
我应该添加/修改什么以避免此错误 属性 'api' 在类型 'Window & 上不存在typeof globalThis'
?
What should I add / modify in order to avoid this error Property 'api' does not exist on type 'Window & typeof globalThis'
?
- 节点:v14.5.0
- 电子:v11.2.3
- 打字稿:v4.1.3
- 操作系统:Ubuntu 18.04.4 桌面
推荐答案
我不熟悉 React.js,但我在使用 Electron-Angular 应用程序时遇到了同样的问题.通过将以下声明添加到我的 app.module.ts 文件中,它允许 TypeScript 识别窗口中的 api
对象.
I'm not familiar with React.js but I had the same issue with an Electron-Angular application. By adding the following declaration to my app.module.ts file it allows TypeScript to recognize the api
object in window.
您应该能够通过添加到您的 TS 项目中的主模块来做同样的事情.
You should be able to do the same by adding to your main module in your TS project.
declare global {
interface Window {
api?: any;
}
}
在您应该能够在项目中的任何位置简单地执行代码之后.
After you should be able to simple execute your code anywhere in your project.
if(window.api) {
window.api.send('ipcChannel', data);
}
这篇关于Window & 类型上不存在属性全局类型This的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!