Skip to content

Instantly share code, notes, and snippets.

@ianks
Created January 6, 2016 16:11
Show Gist options
  • Save ianks/98e1a3d29a4d863cb803 to your computer and use it in GitHub Desktop.
Save ianks/98e1a3d29a4d863cb803 to your computer and use it in GitHub Desktop.
Generic method decorator Typescript
// In this example, I am trying to have a user specify a type for generic decorator function fetchJson.
//
// It would work like this:
// 1. call to `@fetchJson<User>`
// 2. We then replace the function with one that automatically calls `.then(res => res.json())`, and give back
// a typed value in a Promise,
//
// This issue I am running into is that I do not know how to assign the return `descriptor.value` to a user-assigned T.
// Is there a better way to do this? I feel like I am missing something entirely.
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;
};
export default fetchJson;
// 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'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment