[英]Restrict the usage of method decorators
我有一個方法的裝飾器,我希望它只能與異步方法一起使用。 這是用法示例:
class A {
@deco() // This should work.
public async works() { }
@deco() // This should fail.
public fails() { }
}
我試圖這樣定義裝飾器:
export function deco() {
return <T extends {[K in keyof T]: () => Promise<any>},
K extends string>
(target: T,
propertyKey: K,
descriptor: PropertyDescriptor) => {
// Decorator code here.
};
}
但這是行不通的。 它在works
和方法上都fails
因為K
[K in keyof T]
的K
[K in keyof T]
和K
中的K extends string
和propertyKey: K
是不相同的,因此K
不限於是T的鍵。
這也不起作用:
export function deco() {
return <T extends {[K in keyof T]: () => Promise<any>},
K extends keyof T>
(target: T,
propertyKey: K,
descriptor: PropertyDescriptor) => {
// Decorator code here.
};
}
這都不是:
export function deco() {
return <T,
K extends keyof T>
(target: T & {[propertyKey]: () => Promise<any>},
propertyKey: K,
descriptor: PropertyDescriptor) => {
// Decorator code here.
};
}
任何想法?
您應該使用方法裝飾器,而不是屬性裝飾器:
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
可以添加到任何返回諾言的方法中的裝飾器是:
function TypeRestrictedMethodDecorator(
target: Object, // The prototype of the class
propertyKey: string, // The name of the method
descriptor: TypedPropertyDescriptor<(... p:any[]) => Promise<any>>
) {
console.log("TypeRestrictedMethodDecorator called on: ", target, propertyKey, descriptor);
}
class TypeRestrictedMethodDecoratorExample {
@TypeRestrictedMethodDecorator
method(num: number): Promise<number> {
return new Promise((res, rej)=> res(10));
}
@TypeRestrictedMethodDecorator // Error
method2(num: number): number {
return 10;
}
}
從這里修改的示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.