Ilija Ivic
Ilija Ivic

Reputation: 187

Extending a generic type with a constructor function

How to extend a generic type with a constructor function in Typescript?

function doSomething<T extends ?constructor?>(constructor: T) {
    ...
}

Upvotes: 1

Views: 286

Answers (1)

Guerric P
Guerric P

Reputation: 31825

You could do like this:

type Constructor = new (...args: any[]) => any;

class Base {
  baseProp = 'base value';
}

function doSomething<T extends Constructor>(constructor: T) {
    return class extends constructor {
      factoryProp = 'factory prop';
    }
}

const DerivedClass = doSomething(Base);

const instance = new DerivedClass;

console.log(instance.baseProp);
console.log(instance.factoryProp);

TypeScript playground

Upvotes: 1

Related Questions