【问题标题】:Is an array of types possible in Typescript?Typescript 中是否可以使用类型数组?
【发布时间】:2017-09-14 14:16:17
【问题描述】:

我在 Javascript 中使用以下模式:

var things = {
  "blue": BlueThing,
  "heavy": HeavyThing,
  "imaginary": ImaginaryThing
};

var my_thing = things[thing_type]();

我正在将代码库迁移到 Typescript,但我找不到实现相同目标的方法。我已经定义了一个Thing 接口和相关的类。有没有办法在不诉诸 case 声明的情况下实现这种动态实例化?

【问题讨论】:

  • Object.keys(东西)??只是猜测
  • @TomMillard 关键是我无法在 TypeScript 中创建 things 字典,因为类型没有类型。
  • Typescript 是 JavaScript 的超集,all 有效的 Javascript 也是有效的 Typescript。因此,目前还不清楚您遇到了什么问题,或者为什么这段代码不能按原样工作。

标签: javascript typescript


【解决方案1】:

好的,我解决了这个问题。

使用构造函数接口模式,我现在有了这个:

interface ThingConstructor {
  new (options: {[key: string]: string}) : Thing
}

interface Thing{
  /* * */
}

function thingFactory(type: ThingConstructor) : Function{
  return function(options) : Thing {
    return new type(options)
  }
}

--------

things: {[key: string]: Function}

--------

things["blue"] = thingFactory(BlueThing)

var my_thing = things[thing_type]({"stripes": "vertical"})

【讨论】:

  • 也可以指定函数类型? (options) => Thing
猜你喜欢
  • 1970-01-01
  • 2019-09-24
  • 2019-12-13
  • 2013-01-16
  • 2023-01-03
  • 1970-01-01
  • 2022-11-24
相关资源
最近更新 更多