2015-12-30 79 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; 
相关问题