mtizziani
mtizziani

Reputation: 1016

Do nothing if setter or property is not defined in Typescript Object?

Is it possible to check if there is no setter defined in Typescript Object?

I have following code:

class Sample {
  private _name;

  set name(value: string) {
    value = value.trim();
    if(value.length > 0)
      this._name = value;
  }

  get name(): string {
    return this._name;
  }
}

i set the values by a change listener in my html forms.

the problem is, if i have a form element what shows on a not defined object property it simply sets it.

sample = new Sample();
sample.name = "myName";
sample.myTest = true;

returns an object like this:

{
  name: "myName";
  myTest: true;
}

how can i prevent undefined properties will not be set?

using sample.hasOwnProperty(propertyName) allways returns false. sample.hasOwnProperty('_' + propertyName) also returns false.

sample[propertyName] === undefined returns true on sample.name because there is not value set on initializing an object.

Upvotes: 0

Views: 1601

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

You can check if the instance constructor.prototype has the property:

let sample = new Sample();
console.log(sample.constructor.prototype.hasOwnProperty("name")); // true

let object = {};
console.log(object.constructor.prototype.hasOwnProperty("name")); // false

(code in playground)

Upvotes: 2

Related Questions