简体   繁体   English

您将如何在 TypeScript 中创建通用工厂类型?

[英]How would you create a generic Factory type in TypeScript?

I'm trying to create a generic typescript type for factories.我正在尝试为工厂创建一个通用的 typescript 类型。

I started with this class:我从这个 class 开始:

class Car {
    private brand: string;

    constructor(brand: string) {
        this.brand = brand;
    }

    printBrand() {
        console.log(this.brand);
    }
}

and created the following type:并创建了以下类型:

type CarFactory = (...args: ConstructorParameters<typeof Car>) => Car;

so then i could create the factory function:这样我就可以创建工厂 function:

const createCar: CarFactory = (brand: string) => {
    return new Car(brand);
};

Here is my question: is it possible to define a generic type like:这是我的问题:是否可以定义一个通用类型,例如:

type Factory<T> = (...args: any[]) => T;

without using any[] and having a constraint on the constructor parameters for T?不使用any[]并且对 T 的构造函数参数有约束?

After talking to @Tobias S. i edited my question to post the solution i found:在与@Tobias S 交谈后,我编辑了我的问题以发布我找到的解决方案:

type Factory<T extends new (... args: any[]) => any> = (... args: ConstructorParameters<T>) => InstanceType<T>;

type CarFactory = Factory<typeof Car>;

const createCar: CarFactory = (brand: string) => {
    return new Car(brand);
};

createCar('Peugeot').printBrand();

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

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