2015-12-30 119 views
0

我正在做一些重構,想知道是否可以聲明和初始化一個工廠函數的字典,鍵入一個枚舉器,以便它可以用作工廠函數的查找,然後可以調用它?或者,或者,我是否會錯誤地解決這個問題,並且缺少更優雅的解決方案。我遵循this answer來聲明和初始化一個類型化的字典,但我不確定我是否已經聲明瞭簽名是否正確,使得該鍵是一個數字,並且該值是一個函數。我將代碼簡化爲一個非常通用的示例 - 我知道它很人造,但意圖更清晰。是否可以在TypeScript中聲明和調用函數字典?

// Types are enumerated as I have several different lists of types which I'd like to 
// implement as an array of enumerators 
enum ElementType { 
    TypeA, 
    TypeB, 
    TypeC 
} 

// Here, I'm trying to declare a dictionary where the key is a number and the value is a 
// function 
var ElementFactory: { [elementType: number]:() => {}; }; 

// Then I'm trying to declare these factory functions to return new objects 
ElementFactory[ElementType.TypeA] =() => new ElementOfTypeA(); 
ElementFactory[ElementType.TypeB] =() => new ElementOfTypeB(); 
ElementFactory[ElementType.TypeC] =() => new ElementOfTypeC(); 

// And finally I'd like to be able to call this function like so such that they return 
// instantiated objects as declared in the code block above 
var a = ElementFactory[ElementType.TypeA](); 
var b = ElementFactory[ElementType.TypeB](); 
var c = ElementFactory[ElementType.TypeC](); 
+1

這主要是正確的,但在你的類型定義'()=> {}'說:「這是一個函數,它不帶參數,並返回一個'{}'」 。您可能希望將該返回類型更改爲比「{}'更具體的內容,但請注意,您無法爲單個索引指定不同的返回類型。 – DCoder

+0

謝謝@DCoder,我相信那就是我錯過的!你能把這個答案放在答案中,我會將其標記爲已接受? –

回答

1

您的代碼大多是正確的,這種方法將工作,但有一兩件事是可以改進:

// Here, I'm trying to declare a dictionary where the key is a number and the value is a 
// function 
var ElementFactory: { [elementType: number]:() => {}; }; 

在一個類型定義,() => {}的意思是「一個函數,零參數並返回{}「。您可以在這裏修改返回類型,使其更具體,但不幸的是,只要您調用這些工廠函數,您仍然需要手動表示返回值的類型。例如,你可以這樣做:

type AnyElementType = ElementOfTypeA | ElementOfTypeB | ElementOfTypeC; 

var ElementFactory: { [elementType: number]:() => AnyElementType; }; 

... 

// this type declaration will not work 
var a: ElementOfTypeA = ElementFactory[ElementType.TypeA](); 

// but these will 
var b = <ElementOfTypeB>ElementFactory[ElementType.TypeB](); 
var c = ElementFactory[ElementType.TypeC]() as ElementOfTypeC; 
相關問題