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]();
這主要是正確的,但在你的類型定義'()=> {}'說:「這是一個函數,它不帶參數,並返回一個'{}'」 。您可能希望將該返回類型更改爲比「{}'更具體的內容,但請注意,您無法爲單個索引指定不同的返回類型。 – DCoder
謝謝@DCoder,我相信那就是我錯過的!你能把這個答案放在答案中,我會將其標記爲已接受? –