I am adding an additional property to the class using a property decorator. Obviously the compiler will complain that type does not exist in the class. How can I add type notation for the compiler?
function mydecorator(target, key): void {
let value: string;
Object.defineProperty(target, 'myDynamicProperty', {
get: (): string => value,
set: (v: string): void => {value = v},
configurable: true, enumerable: true
});
}
class MyGreatClass {
@mydecorator
theOrignalProperty: string;
}
Now when accessing myDynamicProperty it will give an error.
const myInstance = new MyGreatClass();
// TS2339: Property 'myDynamicProperty' does not exist on type 'MyGreatClass'.
myInstance.myDynamicProperty = 'some value';
How to remove this error and give IDE and compiler hint's that a dynamically added property exists?
To make compiler know that this property exists you should declare it. The problem is that compiler may complain that it is never assigned a value, but this can be fixed with an exclamation point:
A question is why you apply decorator to
theOriginalPropertyif you don't do anything with it in the decorator, but well I assume you know what you're doing