MohanaRajesh
MohanaRajesh

Reputation: 51

Property not available after applying decorator in typescript

I just want to add decorator and without affecting the instance creation.

Here is the sample code

function Min(limit: number) {
  return function(target: Object, propertyKey: string) { 
    let value : string;
    const getter = function() {
      return value;
    };
    const setter = function(newVal: string) {
       if(newVal.length < limit) {
        Object.defineProperty(target, 'errors', {
          value: `Your password should be bigger than ${limit}`
        });
      }
      else {
        value = newVal;
      }      
    }; 
    Object.defineProperty(target, propertyKey, {
      get: getter,
      set: setter
    }); 
  }
}
class User {
    username: string;
    @Min(8)
    password: string;
    constructor(username: string, password: string){
        this.username = username;
        this.password = password;
    }    
}

let user = new User("dany", "pass");
    console.log(user);  // This gives only { username: 'dany' } 

creating new User() is giving only { username: 'dany' } password is not available in the new instance.

why the password is not part of user?

Upvotes: 1

Views: 185

Answers (1)

Surya Prakash Tumma
Surya Prakash Tumma

Reputation: 2193

By default, properties you define with defineProperty are not enumerable - this means that they will not show up when you iterate or console the object

You need to access the property from the object like

console.log(user.password)

and I see a issue in the setter when the newvalue is less than limit you are not assigning the newValue to value;

it should be like below.

const setter = function (newVal: string) {
    if (newVal.length < limit) {
    Object.defineProperty(target, 'errors', {
      value: `Your password should be bigger than ${limit}`
    });

  }
  value = newVal;
}; 

Upvotes: 1

Related Questions