And*_*ies 5 dictionary enumeration factory function 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]();
Run Code Online (Sandbox Code Playgroud)
您的代码大部分是正确的,这种方法会起作用,但有一点可以改进:
Run Code Online (Sandbox Code Playgroud)// 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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6393 次 |
| 最近记录: |