Skip to content Skip to sidebar Skip to footer

Typescript, Generic Variadic Factory Function Returning Tuple

In typescript, a factory function can be created like this, with a return type defined: function factory1(object: new () => T): T { return new object(); } If I want

Solution 1:

Sure, you can make the factory rest argument a mapped array/tuple type. You'll need a type assertion or something like it to convince the compiler that the returned value in the body is really a [...T]:

function factory<T extendsany[]>(...ctors: { [K in keyof T]: new () => T[K] }) {
    return ctors.map(x =>new x) as [...T];
}

You can verify that this works:

classA {
    x = 1;
}
classB {
    u = "u";
}
classC {
    s = true;
}

const objects = factory(A, B, C);
// const objects: [A, B, C]
console.log(JSON.stringify(objects)); // [{"x":1},{"u":"u"},{"s":true}] 

Playground link to code

Post a Comment for "Typescript, Generic Variadic Factory Function Returning Tuple"