2016-01-06 3 views
8

このコードでは、ユーザがジェネリックデコレータ関数fetchJsonの型を指定させようとしています。Typescriptでジェネリックメソッドデコレータを作成する

それはこのように動作します:

  1. のようなものを持つメソッド飾り:@fetchJson<User>
  2. 我々は、自動的に.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'. 

答えて

7

このような何か:

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) 
    { 
     //.... 
    } 
} 
関連する問題