2016-01-22 36 views
3

我有這個簡單的類與具有應用了property decorator屬性:如何將其他參數傳遞給TypeScript中的屬性裝飾器?

class MyClass { 
    @collectionMember 
    public myProperty: number[]; 

    // ... 
} 

而且裝飾功能:

function collectionMember(target: Object, propertyKey: string | symbol): void { 
    // ... 
} 

如何傳遞額外參數的裝飾功能?我試圖做有沒有用下列內容:

class MyClass { 
    @collectionMember("MyProp") 
    public myProperty: number[]; 

    // ... 
} 

很顯然,這會產生錯誤

提供的參數不匹配,通話對象的任何簽名。

回答

9

它可以通過使用裝飾工廠來完成。

工廠,僅僅是一個裝飾簽名收到你想要的任何參數和返回功能的功能:

// any parameters, even optional ones! 
function collectionMember(a: string, b?: number) { 
    // the original decorator 
    function actualDecorator(target: Object, property: string | symbol): void { 
     // do something with the stuff 
     console.log(a); 
     console.log(target); 
    } 

    // return the decorator 
    return actualDecorator; 
} 

然後像你描述你可以使用它。

class MyClass { 
    @collectionMember('MyProp') // 2nd parameter is not needed for this array 
    public myProperty: number[] = [1, 2, 3, 4, 5]; 

    // ... 
} 
+0

有從'@ collectionMember'裝飾訪問類'MyClass'他人財產的一種方式?假設我在'MyClass'中聲明瞭'app',我可以從裝飾器中訪問'app'嗎? – borislemke

相關問題