Here is an example code snippet:
interface ValueGenerator {
next(): any;
}
class NumberGenerator {
next(): number {
return 1;
}
}
class ArrayMaker<T extends ValueGenerator> {
private generator: T;
constructor(valueGenerator: T) {
this.generator = valueGenerator;
}
makeArray(): Array<ReturnType<T['next']>> {
return [this.generator.next()];
}
}
const numGen = new NumberGenerator();
const func1 = <T extends ValueGenerator>(t: T) => new ArrayMaker(t);
const func2 = (...args: ConstructorParameters<typeof ArrayMaker>) => new ArrayMaker(...args)
const array1 = func1(numGen);
const array2 = func2(numGen);
// Generates a number[]
const result1 = array1.makeArray();
// Generates any[]
const result2 = array2.makeArray();
Looking for a way to create a factory function for ArrayMaker
without writing the correct signature manually like in func1
? It would be ideal to use something similar to func2
, but it's not working as expected. While func2
infers the constructor parameters correctly, it doesn't infer the return type of array2.makeArray
.