我想编写一个TypeScript方法装饰器,该装饰器只能应用于具有某种类型的第一个参数的方法。这是我正在使用的代码库中的一种常见模式,用于传递具有数据库,指标,日志记录等句柄的请求上下文。我想编写一个在请求上下文中需要这些资源之一的装饰器,但是否则与请求上下文的形状无关。
这是一个程式化的示例:
interface MyResource {
logMetricsEtc(...args: any): void;
}
interface HasResourceINeed {
myResource: MyResource;
}
function myDecorator<TFn extends ((tContext: HasResourceINeed,...rest: any) => any)>(
_target: object,key: string | symbol,descriptor: TypedPropertyDescriptor<TFn>,): TypedPropertyDescriptor<TFn> | void {
const originalHandler = descriptor.value!;
descriptor.value = function (this: any,context: HasResourceINeed,...inputs: any) {
context.myResource.logMetricsEtc(...inputs);
return originalHandler.apply(this,[context,...inputs]);
} as TFn;
}
在使用中,启用strictFunctionTypes
时,此装饰器在应用于看起来合理的方法时会导致编译错误:
interface ServiceContext {
myResource: MyResource;
otherResource: {
sendMessageEtc(msg: string): Promise<void>;
};
}
class MyBusinessClass {
// This causes a compile error,but shouldn't - the decorator will
// work here at runtime.
@myDecorator
async foo(context: ServiceContext,x: number): Promise<void> {
}
// This example MUST cause a compile error to prevent invalid
// usage - there's no resource available in the first arg for the
// decorator to use.
@myDecorator
async bar(y: string): Promise<void> {
}
}
不需要的编译错误如下:
Argument of type 'TypedPropertyDescriptor<(context: ServiceContext,x: number) => Promise<void>>' is not assignable to parameter of type 'TypedPropertyDescriptor<(tContext: HasResourceINeed,...rest: any) => any>'.
Types of property 'value' are incompatible.
Type '((context: ServiceContext,x: number) => Promise<void>) | undefined' is not assignable to type '((tContext: HasResourceINeed,...rest: any) => any) | undefined'.
Type '(context: ServiceContext,x: number) => Promise<void>' is not assignable to type '(tContext: HasResourceINeed,...rest: any) => any'.(2345)
我无法合理地关闭strictFunctionTypes
。有没有办法编写装饰器类型以接受foo
但拒绝bar
?