本文介绍了如何为属性创建TypeScript @enumerable(false)装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在TypeScript中创建一个装饰器,以便能够使类属性不可枚举。
I want to create a decorator in TypeScript in order to be able to make a class property not enumerable.
我在这里找到了@enumerable的示例:
,但这似乎仅适用于方法,不适用于属性:
I found an example of @enumerable here:https://www.typescriptlang.org/docs/handbook/decorators.html#method-decoratorsbut that only seems to work for methods, not properties:
是否可以为类属性创建@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)装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!