我正在尝试创建一个工厂,以使用泛型实例化我的类。签出TypeScript docs,一切都很好。简而言之,这很好用:

class Person {
    firstName = 'John';
    lastName = 'Doe';
}

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(Person);

console.log(JSON.stringify(person));


现在在directory中定义Person类:

export class Person extends BasePerson {
    firstName = 'John';
    lastName = 'Doe';
}


当我从其他包中导入Person时:

import { Person } from "./directory"

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(Person);


我得到错误:
Argument of type 'typeof Person' is not assignable to parameter of type 'new () => Person'

如何获得Person而不是typeof Person的值?

使用TypeScript 3.7.2和Node v10.13.0。

最佳答案

你能帮我试试吗?

import { Person } from "./directory"

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(new Person);

09-10 10:30
查看更多