Home > Mobile >  How to dynamically select a class property based on the argument of a method
How to dynamically select a class property based on the argument of a method

Time:07-20

I have the following class:

class Person { 
  name: string;
  address: string;
  color: string;
    
  addParameterValue(parameterName: string, value: string){
    if (parameterName == 'name'){
      this.name = value;
    }
    if (parameterName == 'address'){
      this.address = value;
    }
  }
}

I need to make this more dynamically, not an long if-statement, in such way that

const person = new Person()
person.addParameterValue('color', 'blue')
console.log(person.color) //'blue'

I have tried a couple of code snippets like

this[parameterName] = value;

But it gives the following error

No index signature with a parameter of type 'string' was found on type 'Person'.

Code snippet suggested by @jonrsharpe implemented:

addParameterValue(parameterName: keyof Person, value: string){
        this[parameterName] = value
}

gives the following error (but might be a step in the right direction):

Type 'string' is not assignable to type '(parameterName: keyof Person, value: string) => void'.

CodePudding user response:

One thing you could do is this, group the properties into an object which is indexable. However, I have to say that whatever it is you're doing to me would be indicative of messy or bad code. You probably should just do the if statement, sure it's longer but it's clearer what you're doing. Even better would be getting rid of addParamterValue all together and just having functions setName, setAddress, setColor.

Code doesn't have to be short, it has to be clear. If you do things like this all the time your code will become difficult to refactor, difficult to build on, and difficult for others to understand.

type Keys = "name" | "address" | "color";

type Properties = {
  name: string;
  address: string;
  color: string;
}

class Person  { 
  props: Properties;

  constructor(name: string, address: string, color: string) {
    this.props = {name, address, color};
  }
    
  addParameterValue(parameterName: keyof Properties, value: string){
    this.props[parameterName] = value;
  }
}

CodePudding user response:

You can access an object parameter in multiple ways, this method works in your case:

class Person {
    addParameterValue(parameterName: string, value: string) {
        this[parameterName] = value
    }
}
const person = new Person()
person.addParameterValue('color', 'blue')
console.log(person['color'])
  • Related