【问题标题】:How can I declare that a parameter IS a type and not and instance of type in Typescript?如何在 Typescript 中声明参数是类型而不是类型的实例?
【发布时间】:2016-10-19 22:27:10
【问题描述】:

给定

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游乐场Link

【问题讨论】:

  • 我不确定你的目标是什么。你能具体说明你的问题吗?如果你有新的 X,为什么要说 new theType?

标签: typescript typescript1.8


【解决方案1】:

使用typeof 类型运算符获取特定值的类型(在您的情况下为X):

someMethod(myCtor: typeof X) {
   let f: X = new myCtor(); // OK
}

【讨论】:

  • 我希望传入类型。这里 X 是静态的。我会更详细地更新我的问题。
  • 所以让 X = function SomeType(){ };类 MyClass{ someMethod(myCtor: typeof X) { let f: X = new myCtor(); // OK } } 不行。
【解决方案2】:

你需要将构造函数作为参数传递,因为public static create&lt;T&gt;(message:string)中的&lt;T&gt;只是帮助typescript推断类型信息,在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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多