我可以通過應用方法的型別來限制方法裝飾器的引數嗎?
我試圖通過使用來掌握裝飾器所應用的方法的型別TypedPropertyDescriptor<Method>。但是,型別系統并沒有抱怨。
function MyCache<Method extends (...args: any[]) => Promise<any>>(keyFn: (...args: Parameters<Method>) => string) {
return function (target: object, methodName: string, descriptor: TypedPropertyDescriptor<Method>) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: Parameters<Method>) {
const cacheKey = keyFn(...args);
return originalMethod?.apply(this, args);
} as Method;
};
}
class CounterService {
// This should error as the signature of this function does not match the argument list of the method
@MyCache((id: string) => `test-${id}`)
async getCounter(config: { valid: boolean }, value: number): Promise<number> {
return 0;
}
}
在這里試試Typescript Playground
uj5u.com熱心網友回復:
你需要稍微扭轉一下你的想法。您不能將引數限制為裝飾器,但可以限制應用裝飾器的方法。這是因為首先檢查裝飾器工廠函式呼叫,然后根據目標檢查生成的裝飾器。
我們需要做的第一個更改是洗掉 的使用Parameters,因為這將阻止從傳遞給的引數進行推斷MyCache。然后,如果我們只是更改TypedPropertyDescriptor型別引數,我們會得到所需的錯誤:
function MyCache<A extends any[]>(
keyFn: (...args: A) => string
) {
return function (target: object, methodName: string, descriptor: TypedPropertyDescriptor<(...args: A) => Promise<any>>) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: A) {
const cacheKey = keyFn(...args);
return originalMethod!.apply(this, args);
};
};
}
class CounterService {
// Error
@MyCache((id: string) => `test-${id}`)
async getCounter(config: { valid: boolean }, value: number): Promise<number> {
return 0;
}
// ok
@MyCache((id: string) => `test-${id}`)
async getCounter2(id: string): Promise<number> {
return 0;
}
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517337.html
下一篇:React鉤子/異步行為的問題
