gpt4 book ai didi

generics - 在 Typescript 中创建通用方法装饰器

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:02 25 4
gpt4 key购买 nike

在这段代码中,我试图让用户为通用装饰器函数 fetchJson 指定一个类型。

它会像这样工作:

  1. 用类似的东西装饰一个方法:@fetchJson<User>
  2. 然后我们用自动调用 .then(res => res.json()) 的函数替换该函数,并返回一个包装在 Promise 中的键入值。

我遇到的问题是我不知道如何分配返回 descriptor.value给用户指定的 T。有一个更好的方法吗?我觉得我完全错过了一些东西。

interface PromiseDescriptorValue<T>{
(...args: any[]): Promise<T>;
}

const fetchJson = <T>(
target: Object,
propertyKey: string,
descriptor: TypedPropertyDescriptor<PromiseDescriptorValue<Response>> // Response is a whatwg-fetch response -- https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/whatwg-fetch/whatwg-fetch.d.ts#L58
): TypedPropertyDescriptor<PromiseDescriptorValue<T>> => {
const oldMethod = descriptor.value;

descriptor.value = function(...args: any[]) {
return oldMethod.apply(this, args).then((res: Response) => res.json());
};

return descriptor;
};


// TS2322: Type 'TypedPropertyDescriptor<PromiseDescriptorValue<Response>>'
// is not assignable to type
// 'TypedPropertyDescriptor<PromiseDescriptorValue<T>>'. Type
// 'PromiseDescriptorValue<Response>' is not assignable to type
// 'PromiseDescriptorValue<T>'. Type 'Response' is not assignable to type 'T'.

最佳答案

也许是这样的:

interface PromiseDescriptorValue<T>{
(...args: any[]): Promise<T>;
}

export function fetchJson<T>(): any
{
return (
target: Object,
propertyKey: string,
descriptor: any): TypedPropertyDescriptor<PromiseDescriptorValue<T>> =>
{
const oldMethod = descriptor.value;

descriptor.value = function(...args: any[])
{
return oldMethod.apply(this, args).then((res: Response) => res.json());
};

return descriptor;
};
}

class C
{
@fetchJson<User>()
foo(args)
{
//....
}
}

关于generics - 在 Typescript 中创建通用方法装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34637792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com