From da478de53e11ab2e0dc5d32bc457be3d3e144079 Mon Sep 17 00:00:00 2001 From: xaviergonz Date: Fri, 18 Oct 2019 23:18:22 +0200 Subject: [PATCH] fix async generator typing in flows --- src/api/flow.ts | 6 ++++-- test/base/typescript-tests.ts | 19 +++++++++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/api/flow.ts b/src/api/flow.ts index a078d3110..4f0c64d7e 100644 --- a/src/api/flow.ts +++ b/src/api/flow.ts @@ -5,7 +5,7 @@ let generatorId = 0 export type CancellablePromise = Promise & { cancel(): void } export function flow( - generator: (...args: Args) => Generator + generator: (...args: Args) => Generator | AsyncGenerator ): (...args: Args) => CancellablePromise { if (arguments.length !== 1) fail( @@ -18,7 +18,9 @@ export function flow( const ctx = this const args = arguments const runId = ++generatorId - const gen = action(`${name} - runid: ${runId} - init`, generator).apply(ctx, args) + const gen = action(`${name} - runid: ${runId} - init`, generator as ( + ...args: Args + ) => Generator).apply(ctx, args) let rejector: (error: any) => void let pendingPromise: CancellablePromise | undefined = undefined diff --git a/test/base/typescript-tests.ts b/test/base/typescript-tests.ts index 0b5fd931d..5fa4260da 100644 --- a/test/base/typescript-tests.ts +++ b/test/base/typescript-tests.ts @@ -1557,9 +1557,9 @@ test("it should support asyncAction as decorator (ts)", async () => { class X { @observable a = 1 - f = mobx.flow(function* f(initial: number): any { + f = mobx.flow(function* f(this: X, initial: number) { this.a = initial // this runs in action - this.a += yield Promise.resolve(5) + this.a += yield Promise.resolve(5) as any this.a = this.a * 2 return this.a }) @@ -1590,7 +1590,7 @@ test("flow support async generators", async () => { total += number } return total - } as any) // TODO: fix typings + }) const p = start() const res = await p @@ -1615,7 +1615,7 @@ test("flow support throwing async generators", async () => { total += number } return total - } as any) // TODO: fix typings + }) const p = start() try { @@ -1647,3 +1647,14 @@ test("verify #1528", () => { expect(appState.timer).toBe(0) }) + +test("type of flows that return promises", async () => { + mobx.configure({ enforceActions: "observed" }) + + const f = mobx.flow(function* f() { + return Promise.resolve(5) + }) + + const n: number = await f() + expect(n).toBe(5) +})