是否可以在TypeScript中声明和调用函数字典?

时间:2015-12-30 13:04:27

标签: function dictionary typescript factory enumeration

我正在进行一些重构,并且想知道是否可以声明并初始化工厂函数字典,键入枚举器,这样它就可以用作工厂函数的查找哪个可以被称为?或者,或者,我是否对此采取了错误的方式,并且错过了更优雅的解决方案。我跟着this answer声明并初始化了一个打字字典,但我不确定我是否宣布签名是否正确,这样键就是一个数字而值是一个函数。我已经将我的代码简化为一个非常通用的示例 - 我意识到它相当做作,但意图更加清晰。

// 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 个答案:

答案 0 :(得分: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;