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,我相信那就是我错过的!你能把这个答案放在答案中,我会将其标记为已接受? –