2016-01-22 64 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

相关问题