L
L
lightalex2020-10-02 21:06:09
typescript
lightalex, 2020-10-02 21:06:09

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;
}

Accordingly, you can do this:
class RandomClass {
  start(arg1: string, arg2: number) { /* ... */ }
}
let instance = wrapper(RandomClass, 'Hello, world!', 777);

But since I have it written , the code editor (for example, Visual Code) does not understand what arguments should go next, and I, as a programmer, have to think for myself which parameters I should pass. Is it possible to somehow rewrite the generic so that after I write the first argument to target, then subsequent arguments are taken from target.prototype.init? That is, if we return to the example above, so that after entering the code editor tells me that I should enter more . Is it even possible? Or is TypeScript not that flexible yet? 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

1 answer(s)
A
Aetae, 2020-10-02
@lightalex

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 question

Ask a Question

731 491 924 answers to any question