2016-01-06 12 views
8

W tym kodzie próbuję ustawić, aby użytkownik określił typ dla ogólnej funkcji dekoratora fetchJson.Tworzenie ogólnego dekoratora metod w maszynie opisowej

To działa tak:

  1. Ozdoby metodę z czymś takim: @fetchJson<User>
  2. Następnie zastąpić funkcję z jednym, które automatycznie wywołuje .then(res => res.json()) i oddać wartości wpisywanych owinięte w obietnicę.

Problem używam do jest to, że nie wiem jak przypisać powrót descriptor.value użytkownikowi przypisany T. Czy istnieje lepszy sposób to zrobić? Czuję, że zupełnie coś przeoczyłem.

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'. 

Odpowiedz

7

Może coś takiego:

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) 
    { 
     //.... 
    } 
} 
Powiązane problemy