Over on the TypeScript's Decorator reference page, there is a code snippet showcasing how to override a constructor with a class decorator:
function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
newProperty = "new property";
hello = "override";
}
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
console.log(new Greeter("world"));
Which logs the following:
class_1 {
property: 'property',
hello: 'override',
newProperty: 'new property' }
All seems fine so far. However, attempting to access newProperty
using dot notation results in the error message:
Property 'newProperty' does not exist on type 'Greeter'.ts(2339)
The error is not listed in hints from VS Code and accessing it with bracket notation prompts the warning:
Element implicitly has an 'any' type because type 'Greeter' has no index signature.ts(7017)
Is something missing here? How can one implement adding new properties via Decorators in a type-safe manner? The goal is to have proper compiler support similar to regular class members.