Home > Mobile >  How to create dynamic class property in typescript
How to create dynamic class property in typescript

Time:09-28

Consider a class like this -

class MyClass {
    constructor() {
        const dynamicProperty = {
            name: 'ujjwal gupta',
            setName(value) {
                this.name = value
            }
        };

        for (const key in dynamicProperty) {
            this[key] = dynamicProperty[key];
        }
    }

    getName(){
       return this.name
    }
}

this is valid in javascript, but typescript throws error in getName. I can suppress the error by converting to type any but i need the intillisense.

Please help me

Update 1

My actual use case is -

I have states as object and now i want to create dynamic method to set those states.

const states = {
    name:'ujjwal'
},

class MyMutation {
   constructor(states){
     for(const key in states){
        this[key] = (value)=>{
            states[key] = value;
        }
     }  
   }
}

these methods are available but i also want my class to be strong typed, so that user can see what methods are available or what other properties are available.

if anyone is interested - this is the project i am working on : https://github.com/ujjwalguptaofficial/godam

CodePudding user response:

I would avoid dynamic adding of properties, but in some cases this is the only way.

Here is my solution to this, proven by a typescript playground typescript playground:

type IndexType = {
  [key: string]: any;
}

class MyClass {
    //we are saying - yes we can have any prope with any value, believe me:
    [key: string]: any;

    constructor() {
        const dynamicProperties: IndexType = {
            name: 'ujjwal gupta',
            setName(value: string) {
                this.name = value
            }
        };

        for (const key in dynamicProperties) {
            this[key] = dynamicProperties[key];
        }
    }

    getName(){
       return this.name
    }
}

const instance = new MyClass();


// this will print "ujjwal gupta" to the console
console.log(instance.getName());

//unfortunately we cannot call the setName since it is dynamically appended, but we can call it through the IndexType
instance["setName"]("new value");

// now it will print "new value" to the console
console.log(instance.getName());
  • Related