gpt4 book ai didi

typescript - 如何为属性创建 TypeScript @enumerable(false) 装饰器

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:36 25 4
gpt4 key购买 nike

我想在 TypeScript 中创建一个装饰器,以便能够使类属性不可枚举。

我在这里找到了一个 @enumerable 的例子: https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators但这似乎只适用于方法,不适用于属性:

https://www.typescriptlang.org/docs/handbook/decorators.html#property-decorators

NOTE  A Property Descriptor is not provided as an argument to aproperty decorator due to how property decorators are initialized inTypeScript. This is because there is currently no mechanism todescribe an instance property when defining members of a prototype,and no way to observe or modify the initializer for a property. Assuch, a property decorator can only be used to observe that a propertyof a specific name has been declared for a class.

有没有办法为类属性创建一个@enumerable装饰器?

谢谢

最佳答案

我最终得到了这个解决方案:

/**
* @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

不使用装饰器的相同测试

id 1
name John Doe

关于typescript - 如何为属性创建 TypeScript @enumerable(false) 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40930251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com