给出
Class X{
}
我希望将类作为参数传递给:
someMethod(theType: ?X?){
theType.staticMethod //or
new theType();
}
构造签名(接口)是我唯一的选择吗?
我可能会使用构造签名,但它感觉不自然,构造签名似乎并没有真正传达出新的特定类型。我想我可能会遗漏一些细节。这是一个更详细的示例,但泛型不是运行时类型。
abstract class GreeterBase<T extends GreeterBase<T>>{
message:string;
constructor(message:string){
this.message=message;
}
public static create<T>(message:string):T{
//This is the only part that doesn't work.
return new T(message); //This doesn't work.
}
public abstract greet():string;
public logMessage(){
console.log(this.message);
}
}
class EnglishGreeter extends GreeterBase<EnglishGreeter>{
constructor(message: string) {
super(message);
}
greet() {
return "Hello, " + this.message;
}
}
class FriendlyMessager<T extends GreeterBase<T>>{
private _myGreeter:T;
constructor(andSoForth:string){
this._myGreeter = GreeterBase.create<T>(andSoForth);
this._myGreeter.logMessage();
}
public sendGreeting(){
this._myGreeter.greet();
}
}
let messager = new FriendlyMessager<EnglishGreeter>(', how are you');
messager.sendGreeting();
TS Playground Link
答案 0 :(得分:1)
您需要将构造函数作为参数传递,因为<T>
中的public static create<T>(message:string)
只是帮助打字稿来推断类型信息,这些信息将在js中丢失。
public static create<T>(message:string, cTor: {new(string): T;}):T{
//This is the only part that doesn't work.
return new cTor(message); //This doesn't work.
}
我认为你应该重新设计课程。也许like this
答案 1 :(得分:0)
使用typeof
类型运算符获取特定值的类型(在您的情况下为X
):
someMethod(myCtor: typeof X) {
let f: X = new myCtor(); // OK
}