2017-04-03 52 views
0

我想指定一些覆盖事件,这些事件会给我一个电子应用程序的类型安全。扩充进口打字稿模块接口

对于我的类型:

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

正确的语法,以增加WebContents接口:

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

在此之后,你会看到超载选项在send(...)

enter image description here

UPDATE

你可以把它放在你的声明文件(例如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; 
     } 
    } 
} 
+0

啊谢谢,工作。不幸的是,我期待的副作用,如果我没有正确的价值arg的错误不起作用,我不确定如果可能。 – Tal

+0

我已经阅读了一些文档,但无法弄清楚在我的代码中放置这样的声明的位置。我可以在哪里放置该文件,以及如何配置我的编译选项以查看它? – Tal

+1

原始'event.sender.send(...)'的问题在于它接受'any'作为第二个参数的类型,因此每个其他类型的扩充语句都不同。关于模块扩充,您可以为此创建特定的文件(例如custom-typings.d.ts)。你有这个错误吗? – Diullei