How to give typescript compiler hints for dynamically defined property to a class

106 views Asked by At

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?

1

There are 1 answers

0
Alex Chashin On

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:

class MyGreatClass {
    @mydecorator
    theOrignalProperty: string;
    myDynamicProperty!: string;
}

A question is why you apply decorator to theOriginalProperty if you don't do anything with it in the decorator, but well I assume you know what you're doing