如何为属性创建TypeScript @enumerable(false)装饰器 [英] How to create a TypeScript @enumerable(false) decorator for a property
问题描述
我想在TypeScript中创建一个装饰器,以便能够使类属性不可枚举。
I want to create a decorator in TypeScript in order to be able to make a class property not enumerable.
我在这里找到了@enumerable的示例:
https://www.typescriptlang.org/docs/handbook/decorators .html#method-decorators
,但这似乎仅适用于方法,不适用于属性:
I found an example of @enumerable here: https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators but that only seems to work for methods, not properties:
https://www.typescriptlang.org/docs/handbook/decorators.html#property-decorators
注意由于如何在$ b $中初始化属性装饰器,因此未将属性描述符作为
属性装饰器的参数提供b TypeScript。这是因为当前没有机制在定义原型成员
时描述实例属性
,也没有办法观察或修改属性的初始化程序。像
这样,属性装饰器只能用于观察已为类声明了特定名称的属性
。
NOTE A Property Descriptor is not provided as an argument to a property decorator due to how property decorators are initialized in TypeScript. This is because there is currently no mechanism to describe an instance property when defining members of a prototype, and no way to observe or modify the initializer for a property. As such, a property decorator can only be used to observe that a property of a specific name has been declared for a class.
是否可以为类属性创建@enumerable装饰器?
Is there a way to create a @enumerable decorator for a class property?
谢谢
推荐答案
我最终得到了以下解决方案:
I ended up with this solution:
/**
* @enumerable decorator that sets the enumerable property of a class field to false.
* @param value true|false
*/
function enumerable(value: boolean) {
return function (target: any, propertyKey: string) {
let descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) || {};
if (descriptor.enumerable != value) {
descriptor.enumerable = value;
descriptor.writable= true;
Object.defineProperty(target, propertyKey, descriptor)
}
};
}
用法:
class User {
id:string;
@enumerable(false)
name: string;
}
测试:
var user = new User();
user.id = 1;
user.name = 'John Doe';
for (key in user){ console.log(key, user[key]);}
输出
id 1
不使用装饰器的相同测试
Same test without the use of the decorator
id 1
name John Doe
这篇关于如何为属性创建TypeScript @enumerable(false)装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!