我正在尝试实现将日志记录添加到网络请求的method decorator,但是遇到了一些编译问题。
我实现了一个function findURLB(){
函数,该函数从log
手动复制类型以构成一个泛型函数,其中MethodDecorator
是可能的最大函数定义。日志记录是非常基本的(根据值的执行,仅需T
个日志记录)。用作示例console.log
方法上的@log
装饰器:
NetworkClient#makeRequest
这是错误:
const log = <T extends (...args: any[]) => any>(
target: Object,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
) => {
if (descriptor.value && typeof descriptor.value === 'function') {
const logIdentifier = String(propertyKey);
const originalValue = descriptor.value;
descriptor.value = (...args: any[]): any => {
console.log(`Start: ${logIdentifier}`);
try {
const returnValue = originalValue(...args);
return returnValue instanceof Promise
? returnValue
.then(response => {
console.log(`Resolved: ${logIdentifier}`);
return response;
})
.catch(error => {
console.log(`Rejected: ${logIdentifier}`);
throw error;
})
: returnValue;
} catch (error) {
console.log(`Error: ${logIdentifier}`);
throw error;
}
};
}
};
interface NetworkClientOptions {
url: string;
}
class NetworkClient {
private _options: NetworkClientOptions;
private constructor(options: NetworkClientOptions) {
this._options = options;
}
static create(options: NetworkClientOptions) {
return new NetworkClient(options);
}
@log
async makeRequest() {
return this._options.url;
}
}
(async () => {
const networkClient = NetworkClient.create({ url: 'http://google.com/' });
await networkClient.makeRequest();
})();
这些最可能的功能类型是相同的,所以这个错误对我来说没有意义。 我查看了Microsoft / TypeScript问题,但似乎没有找到任何匹配的内容。有毛病吗有什么想法吗?
相关$ yarn --silent tsc
fancy-decorators.ts:10:5 - error TS2322: Type '(...args: any[]) => any' is not assignable to type 'T'.
'(...args: any[]) => any' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '(...args: any[]) => any'.
10 descriptor.value = (...args: any[]): any => {
~~~~~~~~~~~~~~~~
Found 1 error.
error Command failed with exit code 2.
:
envinfo