Sign constructor signature to factory method

I am trying to define a method for creating a factory function in the general case, so that I can pass a class to it and get back a function that will instantiate this class. Something like:

function createClassFactory<T> (MyClass: {new(...):T}) {
    return function classFactory(...) {
        return new MyClass(...)
    }
}

To save type information, I would like to classFactoryhave the same signature as the constructor MyClass. Right now I am drawing a space about how this is possible.

Is this possible anyway in another way?

+4
source share
1 answer

, ( , ), .
, , , , (, ):

class Base<T> {
    constructor(props: T) {}
}

type BaseConstructor<C extends Base<P>, P> = {
    new(props: P): C; 
}

interface AProps {}

class A extends Base<AProps> {}

interface BProps {
    x: number;
    y: number;
}

class B extends Base<BProps> {}

interface CProps {
    str: string;
    ok?: boolean;
}

class C extends Base<CProps> {}

function createClassFactory<C extends Base<P>, P> (MyClass: BaseConstructor<C, P>) {
    return function classFactory(props: P) {
        return new MyClass(props);
    }
}

// the following are valid:
let a1 = createClassFactory(A)({});
let b1 = createClassFactory(B)({ x: 3, y: 5 });
let c1 = createClassFactory(C)({ str: "stirng" });
let c2 = createClassFactory(C)({ str: "stirng", ok: true });

// these aren't:
let b2 = createClassFactory(B)({ x: 3, y: "5" });
let c3 = createClassFactory(C)({ ok: true });

// but this one is:
let a2 = createClassFactory(A)({ key: "value" });

( )

- , a2 .
, , .

+1

Source: https://habr.com/ru/post/1652712/


All Articles