8
このコードでは、ユーザがジェネリックデコレータ関数fetchJsonの型を指定させようとしています。Typescriptでジェネリックメソッドデコレータを作成する
それはこのように動作します:
- のようなものを持つメソッド飾り:
@fetchJson<User>
- 我々は、自動的に
.then(res => res.json())
を呼び出すものと機能を交換し、約束に包まれた入力された値をお返しします。
私はに実行している問題は、私は、ユーザーが割り当てたT. に復帰descriptor.value
を割り当てる方法がわからないということですこれを行うには良い方法はありますか?私は何か完全に欠けているように感じる。
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'.