Unknown developer
Unknown developer

Reputation: 5970

Add property to a class instance

Let's consider the following code:

class MyClass{
    x: number;
}

const inst = new MyClass();
inst.x = 8;
inst.y = 9;
inst["z"] = 10;

Typescript compiler is complaining about adding y property in the instance of MyClass. That's not the case with z property.

Is that behaviour based on the fact Typescript tries to keep the same shape for all the instances of a class or something else?

Actually, I am using Angular and I am getting the above behaviour inside the components when trying to assign a value to a property not previously defined e.g.

this.prop = 5;

Upvotes: 0

Views: 1230

Answers (1)

felipedsc
felipedsc

Reputation: 81

Well, the idea of creating classes and using TypeScript is to limit your object properties to the defined ones on it...

inst["z"] works because you're appealing to a vanilla javascript behaviour - what is permitted on TypeScript.

But, if you really need to allow your class to receive new properties, you can change it to:

class MyClass {
    [key: string]: any;
    x: number;
}

Upvotes: 3

Related Questions