Home > OS >  Assign fields of class with object keys in typescript/JS
Assign fields of class with object keys in typescript/JS

Time:11-13

I need to dynamically update the fields of this class dynamically with an object

export default class Foo {

    private accessKey: string;
    private workspaceId: string;
    private api: AxiosInstance;
    public bar: string;
    public name: string;
    ...

...

    private async fetch() {
        try {
            // data contains bar and name value
            const { data } = await this.api.get("/");
            // goal
            this = {...this, ...data};

See goal comment, how can I do this dynamically?

CodePudding user response:

Use Object.assign

class X {
    update(from: Partial<this>) {
        Object.assign(this)
    }
}

CodePudding user response:

Assignments and this

Why assigning to this is disallowed

Disregarding that it's not allowed, you don't want to reassign your this reference.

If it was allowed, we could write this confusing code:

const object = {
  reassignSelf() {
    this = {};
  }
};
const ref = object;

object.reassignSelf();

/* Both ref and object are constant variables,
 * so their values (references) should never change.
 * But by reassigning `this` in object.reassignSelf,
 * what value should this comparison produce?
 */
console.log(ref === object);

Then how to assign to this?

As implied earlier, we don't want to reassign this; we want to reassign its properties:

  1. Static assignment. Example:
    this.bar = data.bar;
    this.name = data.name;
    
  2. Dynamic assignment. Example:
    Object.assign(this, data);
    
  • Related