How would you create a generic Factory type in TypeScript?

Viewed 26

I'm trying to create a generic typescript type for factories.

I started with this 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:

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?

Would the following be correct:

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();
0 Answers
Related