2016-12-02 120 views
1

我想在TypeScript中創建裝飾器,以便能夠使類屬性不可枚舉。如何爲屬性創建TypeScript @enumerable(false)裝飾器

我發現這裏@enumerable一個例子: https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators 但這似乎只爲方法,而不是屬性的作用:

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

音符屬性描述不作爲參數提供給 屬性修飾器由於如何在 TypeScript中初始化屬性修飾器。這是因爲目前還沒有機制可以在定義原型成員 時描述實例屬性,並且無法觀察或修改屬性的初始值設定項。由於 這樣,一個屬性修飾器只能用於觀察一個特定名稱的屬性 已被聲明爲一個類。

有沒有辦法爲類屬性創建一個@enumerable裝飾器?

感謝

回答

4

我結束了此解決方案:

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