[英]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.创建 new User() 仅提供 { username: 'dany' } 密码在新实例中不可用。
why the password is not part of user?为什么密码不是用户的一部分?
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默认情况下,您使用 defineProperty 定义的属性是不可枚举的 - 这意味着当您迭代或控制 object 时它们不会显示
You need to access the property from the object like您需要从 object 访问该属性,例如
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.