2013-06-18 32 views
16

我一直在使用Basarats的優秀Collections庫小幅更新的0.9.0創建類型,如:的typedef就像C/C++

Dictionary<ControlEventType, 
    Dictionary<number, (sender: IControl, 
         eventType: ControlEventType, 
         order: ControlEventOrder, 
         data: any) => void >> 

現在我不希望有完整的每一個寫這篇我使用它的時間。其中一個似乎工作的方法之一是:

export class MapEventType2Handler extends C.Dictionary<ControlEventType, 
               C.Dictionary<number, 
               (sender: IControl, 
               eventType: ControlEventType, 
               order: ControlEventOrder, 
               data: any) => void >> {} 

然後我就可以寫:的

EH2: MapEventType2Handler = new MapEventType2Handler(); 

代替:

EH: Dictionary<ControlEventType, 
     Dictionary<number, 
     (sender: IControl, 
     eventType: ControlEventType, 
     order: ControlEventOrder, 
     data: any) => void >>; 

人碰到更好的想法?

我也正在試驗'typedeffing'各種功能簽名沒有很好的結果。

回答

2

首先謝謝你的友好的話:)。

您的解決方案實際上是最佳的。

長答案 Typescript有兩個聲明空間。類型和變量。

引入物品進入類型聲明空間的唯一方法是經由一個類或一個接口(0.8.4可以使用模塊來引入類型以及,其從0.9.x版本移除)

接口不會因爲您希望實現保持不變(並且接口與實現無關)。

變量不起作用,因爲它們不會在類型聲明空間中引入名稱。它們只在變量聲明空間中引入一個名稱。

例如爲:

class Foo {  
} 

// Valid since a class introduces a Type AND and Variable 
var bar = Foo; 

// Invalid since var introduces only a variable so bar cannot be used as a type 
// Error: Could not find symbol. Since compiler searched the type declaration space 
var baz: bar; 

// Valid for obvious reasons 
var x: Foo; 

你想如果語言有一個宏可以做什麼,但現在類+擴展是唯一的方法。

+0

不再是正確的 - 現在有一個辦法,所以這需要更新。 ;) –

20

從1.4版本打字稿支持類型別名(source,也看到this answer):

type MapEventType2Handler = Dictionary<ControlEventType, 
    Dictionary<number, 
    (sender: IControl, 
    eventType: ControlEventType, 
    order: ControlEventOrder, 
    data: any) => void >>; 
+0

[高級類型 - 類型別名](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases)。 – user1338062