所以我有这个方法,我想变成一个装饰器:
function MethodRead< Data, Output extends Mongo.Cursor<Data> >(
method: (...args: any[]) => Output,
opt: IOptions = {}
) {
return (...args: any[]) => {
const sub = doSomeProcessing(method(...args), opt);
return {
ready: () => sub.ready(),
fetch: () => sub.fetch(),
};
};
}
此方法的输入(参数除外)都匹配并且运行良好。
然而,当我试图将它变成装饰器时,似乎打字稿只是没有干净的方式处理这个逻辑...
function DecoratorRead<Data>(opt: IOptions) {
return <C, K extends keyof C> (
target: C,
propName: K,
descriptor: TypedPropertyDescriptor<C[K]>
): TypedPropertyDescriptor<Reader<Data>> => {
descriptor.value = (...args: any[]) => {
const sub = doSomeProcessing(method(...args), opt);
return {
ready: () => sub.ready(),
fetch: () => sub.fetch(),
};
}
return descriptor;
}
}
所以,我用打字稿得到的错误是这样的:
Type 'TypedPropertyDescriptor<C[K]>' is not assignable to type 'TypedPropertyDescriptor<Reader<Data>>'.
Type 'C[K]' is not assignable to type 'Reader<Data>'.
Type '(...args: any[]) => { ready: () => boolean; fetch: () => Data; }' is not assignable to type 'Method<Data>'.
Type '{ ready: () => boolean; fetch: () => Data; }' is not assignable to type 'Data'.
以下是一些其他类型的帮助:
interface IOptions {
auth: boolean;
}
type Method<Data> = (...args: any[]) => Data;
type Reader<Data> = (...args: any[]) => {
ready: () => boolean;
fetch: () => Data;
}
function doSomeProcessing<Data>( data: Data , opt: IOptions ) : {
ready: () => boolean;
fetch: () => Data;
};