2017-04-18 39 views
0

我用下面的方式在Javascript:Typescript中可能的数组类型?

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

var my_thing = things[thing_type](); 

我迁移代码库打字稿,我不能找到一种方法来达到同样的事情。我定义了一个Thing接口和相关的类。有没有办法实现这种动态实例化,而不诉诸于大的case声明?

+0

Object.keys(东西)?只是猜测 –

+0

@TomMillard关键是我无法在TypeScript中创建'things'字典,因为类型没有类型。 – fredley

+0

Typescript是JavaScript的超集,并且** all **有效的Javascript也是有效的Typescript。因此,你不清楚你有什么问题,或者为什么这个代码不能按原样工作。 – Claies

回答

0

好吧,我整理了一下。

使用构造接口模式,我现在有这样的:

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"}) 
+0

也可以指定功能类型吗? '(选项)=>事情' – MinusFour