0

I have a function that takes a class as parameter:

function extendClass(cls = class {}) {
  return class extends cls {
    constructor () {
      super();
      console.log("I extend " + cls.name);
    }
  };
}

I want to remove the default value of the parameter cls and make it required.

What type should the parameter cls have?

Yukulélé
  • 15,644
  • 10
  • 70
  • 94
  • 1
    It could be something like `new () => object` but I don't know that this will be strongly typed enough for your use case – jcalz Feb 22 '20 at 02:38

1 Answers1

0

This is an example of modifying the code you provided based on support for mix-in classes as mentioned TypeScript 2.2 Release Notes.

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

function extendClass<Class extends Constructor<{}>>(cls: Class) {
    return class extends cls {
        constructor(...args: any[]) {
            super(...args);
            console.log("I extend " + cls.name);
        }
    };
}

// Valid example:
class Test {
    constructor() { }
}

const ExtendedClass = extendClass(Test)
new ExtendedClass()

// Invalid examples:
extendClass("a")
extendClass(1)
extendClass({})

TypeScript Playground

skovy
  • 5,430
  • 2
  • 20
  • 34
  • Thanks it works perfectly! but I'm not sure to understand this: `Constructor<{}>` can you explain it? – Yukulélé Feb 22 '20 at 21:34
  • 1
    `{}` is the value for `T`. Where `T` is the generic that represents the return value of a classes' constructor. So this is saying that the input classes constructor returns `{}` – skovy Feb 23 '20 at 01:18