Skip to content Skip to sidebar Skip to footer

Typescript Class Decorator: Override The Constructor But Preserve The Class Name?

The typescript handbook has an example of how to use a class decorator to override the constructor (link): function classDecorator(

Solution 1:

You could try something like this, seems a bit hacky though.

function classDecorator<T extends { new (...args: any[]): {} }>(
  constructor: T
) {
  const cls = class extends constructor {
    newProperty = "new property";
    hello = "override";
  };
  Object.defineProperty(cls, 'name', {
    get: () => `${constructor.name}Generated`
  });
  return cls
}

Post a Comment for "Typescript Class Decorator: Override The Constructor But Preserve The Class Name?"