增加导入的typescript模块接口

时间:2017-04-03 20:39:30

标签: typescript typescript-typings

我试图为电子应用中的类型安全事件指定一些事件的覆盖。

对于我的类型:

export type SectionName = 'webview'
  | 'index'
  | 'settings'

export interface ShowSection {
  key: SectionName,
}

我想补充一下这段代码:

import {
  ipcMain,
} from 'electron'

ipcMain.on('rendered', (event) => {
  const sender = event.sender

  event.sender.send('show-section', {
    key: 'index',
  })
})

发件人的类型为Electron.WebContents,其定义为here

我试图像这样增加:

declare namespace Electron {
  interface WebContents extends NodeJS.EventEmitter {
    send(channel: 'show-section', arg: ShowSection): void;
  }
}

我不知道如何做到这一点,以便我可以在个别事件中获得类型安全。

由于

1 个答案:

答案 0 :(得分:1)

增强WebContents接口的正确语法是:

declare global {
    namespace Electron {
        interface WebContents extends NodeJS.EventEmitter {
            send(channel: 'show-section', arg: ShowSection): void;
        }
    }
}

在此之后,您将看到send(...)上的过载选项:

enter image description here

<强>更新

您可以将其放在声明文件中(例如custom-typings.d.ts):

export interface ShowSection {
    key: SectionName
}

export type SectionName = 
    'webview'
    | 'index'
    | 'settings'

declare global {
    namespace Electron {
        interface WebContents extends NodeJS.EventEmitter {
            send(channel: 'show-section', arg: ShowSection): void;
        }
    }
}
相关问题