简体   繁体   English

TypeScript 泛型创建实例

[英]TypeScript generics create instace

I'm trying to create a factory for instantiating my classes with generics.我正在尝试创建一个工厂,用于使用泛型实例化我的类。 Checked out TypeScript docs and it all works perfectly.查看了TypeScript 文档,一切正常。 In short, this works just fine:简而言之,这很好用:

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));

Now define class Person in directory :现在在directory定义类 Person :

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

And when I import Person from other package:当我从其他包导入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);

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

How can I get a value of Person instead of typeof Person ?如何获得Person而不是typeof Person

Using TypeScript 3.7.2 and Node v10.13.0.使用 TypeScript 3.7.2 和 Node v10.13.0。

Could you try this for me please?你能帮我试试这个吗?

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);

Actual problem here was a parent class of Person -> BasePerson .这里的实际问题是Person -> BasePerson的父类。 BasePerson expected an argument in its constructor, so when I tried to call factory.create(Person) , Person actually was an typeof because it expected an argument for base class constructor. BasePerson在其构造函数中需要一个参数,所以当我尝试调用factory.create(Person)Person实际上是一个typeof因为它需要一个基类构造函数的参数。 Problem was solved by deleting the constructor in base class and injecting a property via ioc container, in my case Inversify .问题是通过删除基类中的构造函数并通过 ioc 容器注入一个属性来解决的,在我的例子中是Inversify

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM