reactjs - 属性在类型 Window 和 typeof globalThis 上不存在
问题描述
在 Electron-React-Typescript 应用程序中,我收到此错误: Property 'api' does not exist on type 'Window & typeof globalThis'. window.api.send('open-type-A-window', '');
但是在 index.d.ts 文件中,我以这种方式声明了接口 Window:
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/issues/19816但我没有得到正确的解决方案。
为了避免这个错误,我应该添加/修改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
窗口中的对象。
您应该能够通过添加到您的 TS 项目中的主模块来做同样的事情。
declare global {
interface Window {
api?: any;
}
}
在您应该能够在项目中的任何位置简单地执行您的代码之后。
if(window.api) {
window.api.send('ipcChannel', data);
}
推荐阅读
- firefox - 新的 Firefox 更新书签工具栏(显示更多书签) | 双空间问题
- regex - 单个正则表达式从 a/b/c/d:Z1234 中提取 a/b/c,从 a/b/c:Y5678 中提取 a/b/c
- woocommerce - 通过 url 在 woocommerce 中添加具有属性的多个产品
- swift - 无法将“Object.Type”类型的值转换为预期的参数类型“Object”
- html - 为什么链接不会在新窗口中打开?
- python - 批量梯度下降中发散的成本函数
- javascript - 分数未显示在屏幕上,但仅显示在控制台日志中
- wordpress - 如何检查插件是否在 post_type 页面类别视图中?
- keystore - 将 AWS IoT SDK v2 与来自 java 密钥库的证书一起使用
- javascript - 联网框架动态房间不能使用简单的 rtc