简体   繁体   中英

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM