【问题标题】:Generic and typeof T in the parameters参数中的 Generic 和 typeof T
【发布时间】:2016-11-13 16:18:55
【问题描述】:

在 TypeScript 中,我可以将变量的类型定义为类的类型。例如:

class MyClass { ... }

let myVar: typeof MyClass = MyClass;

现在我想将它与泛型类一起使用,如下所示:

class MyManager<T> {
    constructor(cls: typeof T) { ... }
    /* some other methods, which uses instances of T */
}

let test = new MyManager(MyClass); /* <MyClass> should be implied by the parameter */

所以,我想给我的管理器类另一个类(它的构造函数),因为管理器需要检索与 关联的静态信息。

编译我的代码时,它说找不到名称“T”,我的构造函数在哪里。

知道怎么解决吗?

【问题讨论】:

    标签: typescript typescript1.8


    【解决方案1】:

    您可以使用这种类型的构造函数:{ new (): ClassType }

    class MyManager<T> {
        private cls: { new(): T };
    
        constructor(cls: { new(): T }) {
            this.cls = cls;
        }
    
        createInstance(): T {
            return new this.cls();
        }
    }
    
    class MyClass {}
    
    let test = new MyManager(MyClass);
    let a = test.createInstance();
    console.log(a instanceof MyClass); // true
    

    (code in playground)


    编辑

    在打字稿中描述类类型的正确方法是使用以下内容:

    { new(): Class }
    

    例如在打字稿中lib.d.ts ArrayConstructor:

    interface ArrayConstructor {
        new (arrayLength?: number): any[];
        new <T>(arrayLength: number): T[];
        new <T>(...items: T[]): T[];
        (arrayLength?: number): any[];
        <T>(arrayLength: number): T[];
        <T>(...items: T[]): T[];
        isArray(arg: any): arg is Array<any>;
        readonly prototype: Array<any>;
    }
    

    这里有 3 个不同的 ctor 签名以及一堆静态函数。
    在您的情况下,您还可以将其定义为:

    interface ClassConstructor<T> {
        new(): T;
    }
    
    class MyManager<T> {
        private cls: ClassConstructor<T>;
    
        constructor(cls: ClassConstructor<T>) {
            this.cls = cls;
        }
    
        createInstance(): T {
            return new this.cls();
        }
    }
    

    【讨论】:

    • { new(): T } 的含义并不是那么明显,尤其是因为构造函数被定义为 constructor(),而人们宁愿期待像 Ttypeof T 之类的东西。
    • 这是定义类类型/ctor的标准方法,请查看我修改后的答案以获取更多信息。
    • @NitzanTomer 您将如何编写构造函数以允许 let test = new MyManager(Array&lt;MyClass&gt;); ?或...MyManager(MyClass[]);
    • @GFoley83 怎么样:constructor(cls: MyClassConstrcutor&lt;T&gt;[])
    • @NitzanTomer 我要找的是constructor(cls: { new (...args: any[]): T } [])
    猜你喜欢
    • 2012-09-23
    • 2022-12-18
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多