Created
July 19, 2017 19:38
-
-
Save laughinghan/f130f065c624f23e1efc03041e944a99 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see this in the TypeScript Playground: https://goo.gl/pmNV6U | |
// foo: (x: string) => IterableIterator<Promise<Response> | Promise<string>> | |
const foo = function* (x: string) { | |
const page: Response = yield fetch(x); // :( can't propagate type to yield https://github.com/Microsoft/TypeScript/issues/2983 | |
return page.text(); | |
}; | |
// TYPE ERROR HERE: | |
// expected bar: (a: string) => Promise<Response | String> | |
const bar = asyncTransact(foo); | |
// I = input, O = output | |
function asyncTransact<I, O1, O2>(genFn: (a: I) => IterableIterator<Promise<O1> | Promise<O2>>): (a: I) => Promise<O1 | O2>; | |
// workaround: fallback to {}, so bar is: (a: string) => Promise<{}>, which isn't ideal but at least doesn't type-error | |
// function asyncTransact<I>(genFn: (a: I) => IterableIterator<{}>): (a: I) => Promise<{}>; | |
function asyncTransact<O>(genFn: (...args: {}[]) => IterableIterator<O>) { | |
return async function (this: {}, ...args: {}[]) { | |
// skeleton of actual code | |
const gen: IterableIterator<O> = genFn.apply(this, args); | |
return await gen.next().value; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment