reactjs - 属性在类型 Window 和 typeof globalThis 上不存在

标签 reactjs typescript electron

在 Electron-React-Typescript 应用程序中,我收到此错误:Property 'api' does not exist on type 'Window & typeof globalThis'. window.api.send('open-type-A-window', '');但是在文件 index.d.ts 中,我以这种方式声明了接口(interface) 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
  • Electron :v11.2.3
  • typescript :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);
    }
    

    关于reactjs - 属性在类型 Window 和 typeof globalThis 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66120513/

    相关文章:

    javascript - React JS - 路由 - 元素类型无效

    javascript - 设置搜索超时

    javascript - Typescript 和 Jquery 语法问题

    typescript - 在 VSCode 中禁用 TSLint

    node.js - 语法错误: Unexpected token … in serialport in node_modules

    node.js - 如何自定义 Electron 应用程序中的菜单?

    node.js - 使用 ws 发送自定义事件

    reactjs - React.PropTypes.node 的 TypeScript 等价物是什么?

    javascript - 当我在 nextjs 上使用 babel 别名时出现 Eslint 错误

    javascript - 如何显示我的 MongoDB 属性?