我正在尝试在TypeScript中构建一个机制,以根据表示类名称的字符串参数返回类的新实例。基本上,我正在尝试创建一个工厂,只是我无法弄清楚如何在TypeScript中执行此操作。在纯JS中,我可以通过将所有类构造函数存储在键/值对象中并调用new ClassDictionary[className]();
来避免这种情况 - 它不是最强大的解决方案,但它适用于这种情况。我似乎无法在TypeScript中获得正确的类型组合和强制转换。有没有更好的办法?我还没有在TypeScript中找到任何工厂模式的例子,所以现在我只是有一点开关语句,这是丑陋且不灵活的。
答案 0 :(得分:4)
您可以为字典中的每个类添加一个函数声明,这可能如下所示(访问:http://www.typescriptlang.org/Handbook#declaration-merging-merging-interfaces):
class MyClass {
myMethod() { return "my return"; }
}
function factory(className: "Date"): Date;
function factory(className: "Number"): Number;
function factory(className: "MyClass"): MyClass;
function factory(className: string) {
var ClassDictionary = {
"Date": Date,
"Number": Number,
"MyClass": MyClass
};
return new ClassDictionary[className]();
}
var d = factory("Date");
/* Its a date. */
alert(d.toISOString());
var n = factory("Number");
/* Now a number. */
alert(n.toPrecision());
var c = factory("MyClass");
/* And now MyClass. */
alert(c.myMethod());
在游乐场(Sample)
中工作或以其他方式
// ...
var ClassDictionary = { };
ClassDictionary["Date"] = Date;
function factory(className: "Date"): Date;
ClassDictionary["Number"] = Number;
function factory(className: "Number"): Number;
ClassDictionary["MyClass"] = MyClass;
function factory(className: "MyClass"): MyClass;
function factory(className: string) {
return new ClassDictionary[className]();
}
// ...
或使用参数:
class MyClass {
constructor(public myReturn: string) { }
myMethod() { return this.myReturn; }
}
var ClassDictionary = { };
ClassDictionary["Date"] = Date;
function factory(className: "Date"): Date;
ClassDictionary["Number"] = Number;
function factory(className: "Number", value?: number): Number;
ClassDictionary["MyClass"] = MyClass;
function factory(className: "MyClass", myReturn: string): MyClass;
function factory(className: string, valueOrMyReturn?: number | string) {
if(valueOrMyReturn) return new ClassDictionary[className](valueOrMyReturn);
return new ClassDictionary[className]();
}
var d = factory("Date");
/* Its a date. */
alert(d.toISOString());
var n = factory("Number", 42);
/* Now a number. */
alert(n.toPrecision());
var c = factory("MyClass", "This is the answer!");
/* And now MyClass. */
alert(c.myMethod());
答案 1 :(得分:1)
让我们想象你有一个类定义:
module UI
{
export class MyClass
{
constructor( data: any )
{}
}
}
你可以使用这种结构:
public static CreateController( data: IControllerData ): any
{
return new data.namespace[data.controller]( data.initializationData );
}
其中数据是JS对象,如下所示:
var data = {
namespace: UI,
controller: "MyClass"// <- this is the class name
initializationData: {} // this is the parameters that you want to pass in constructor
}
创建MyClass类的新实例。