Parag Diwan
Parag Diwan

Reputation: 3936

Modify the instance variable using `property` decorator

All,

is it possible to modify the instance variable using property decorator?

for instance,

const config = [
 a: { },
 b: { },
];

class Test {
    @fetchObjectKey('a')
    public message;  // Should fetch the value against the `key` supplied & assign it to `instance` ?
   
 //...
}

Upvotes: 0

Views: 234

Answers (1)

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11568

// You get better auto completion when its casted as const
const config = <const>{
  a: { foo: 1 },
  b: { foo: 2 }
};

function fetchObjectKey(key: keyof typeof config) {
  return (target: object, propertyKey: string) => {
    Reflect.set(target, propertyKey, config[key].foo);
  };
}

// set property based on argument
class Test {
  @fetchObjectKey("a")
  public message!: number;
}

console.log(new Test().message); // will be 1

Upvotes: 1

Related Questions