Answer the question
In order to leave comments, you need to log in
Is such a generic real in TypeScript?
There is a function in which I pass the class:
function wrapper<T extends { start(...args: any[]): void }>(target: { new(...args: any[]): T }, ...args: any[]): T {
let instance = new target();
instance.start(...args);
return instance;
}
class RandomClass {
start(arg1: string, arg2: number) { /* ... */ }
}
let instance = wrapper(RandomClass, 'Hello, world!', 777);
target: { new(...args: any[]): T }, ...args: any[]
wrapper(RandomClass,
arg1: string, arg2: number
Answer the question
In order to leave comments, you need to log in
Like this with arguments:
function wrapper<T extends { start(...args: unknown[]): unknown }>(target: { new(): T }, ...args: Parameters<T['start']>): T {
let instance = new target();
instance.start(...args);
return instance;
}
class RandomClass {
start(arg1: string, arg2: number) { /* ... */ }
}
let instance = wrapper(RandomClass, 'Hello, world!', 777); /// все ок
let instance2 = wrapper(RandomClass, 777); /// ошибка
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question