2016-03-01 60 views
4

我有一個基類EventEmitter,其具有結合特定事件處理程序的on方法專門簽名參數。我想「申報」的事件可以由特定類發出:打字稿:用於EventEmitter子類事件

class MyClass extends EventEmitter { 
    on(event: 'event1', handler: (arg1: number) => void): void; 
    on(event: 'event2', handler: (arg1: string, arg2: number) => void): void; 
} 

所以我的子類可以發出事件event1event2,但這似乎並沒有被指定正確的方式。 TypeScript(tsc 1.8)正在包含:

error TS2415: Class 'MyClass' incorrectly extends base class 'EventEmitter'. 
    Types of property 'on' are incompatible. 
Type '(event: "event1", handler: (arg1: number) => void) => void' is not assignable to type '(event: string, handler: Function) => void'. 
    Type '(event: "event1", handler: (arg1: number) => void) => void' provides no match for the signature '(event: string, handler: Function): void' 
error TS2382: Specialized overload signature is not assignable to any non-specialized signature. 
error TS2391: Function implementation is missing or not immediately following the declaration. 

那麼,指定我的類可以發出的事件的預期方式是什麼?

編輯:我找到了我正在尋找的名字:Specialized Signatures。但是,它似乎只適用於接口,而不適用於新的TypeScript代碼。

現在我發現anothother question與2015年相同的問題,但是那裏的解決方案看起來不太正確。那麼,現在在TypeScript中還有其他的方法嗎?

回答

2

指定我的類可以發出的事件的預期方式是什麼?

代替使用包含所有類型其更容易單個事件流具有用於每個類型單獨事件流。

這是一個概念我叫TypedEvent。使用它是http://alm.tools/

實現一個例子項目:https://github.com/alm-tools/alm/blob/55a8eb0f8ee411a506572abce92085235658b980/src/common/events.ts#L20-L72

下面是一個例子用法:https://github.com/alm-tools/alm/blob/55a8eb0f8ee411a506572abce92085235658b980/src/server/lang/errorsCache.ts#L10

export let errorsUpdated = new TypedEvent<ErrorsUpdate>(); 
// emit: 
errorsUpdated.emit({} /* this will be type checked */); 
// consume: 
errorsUpdated.on((x)=>null); // x has the correct inferred type 
+0

這可能是一個辦法,但它似乎是一個不同的風格。我想調整現有的node.js('instance.on(eventName,handler)')和HTML DOM('element.addEventListener(eventName,handler)')的風格。 – Simon

+0

標準的node.js風格不是用靜態類型檢查來編寫的。它依賴於文檔而不是代碼時間分析,並且在打字稿中不能很好地模擬。 – basarat

+0

你能用我的示例類和事件給我看一個例子嗎?如果我理解正確,我應該爲每個可能的事件定義一個事件子類。我的模塊不是外部的,我的類共享相同的名稱空間。兩個類可能會發出'event1'/'Event1Event',但具有不同的屬性,具體取決於發出它的類。 – Simon