MobX-State-Tree 流程中的类型化 Yield 表达式

Tho*_*lle 6 typescript mobx mobx-state-tree

在 MobX 状态树 (MST) 中执行异步操作的推荐方法是使用flow,它将生成器函数作为第一个参数,其中每个 Promise 都应该产生。

yield expressions are of type any in TypeScript, but is there any way to automatically type a yield expression in MST?

Example

import { flow, types } from "mobx-state-tree";

type Stuff = { id: string; name: string };

function fetchStuff(): Promise<Stuff[]> {
  return new Promise((resolve) => {
    resolve([
      { id: "1", name: "foo" },
      { id: "2", name: "bar" }
    ]);
  });
}

const Thing = types.model({
  id: types.identifier,
  name: types.string
});

const ThingStore = types
  .model({
    things: types.array(Thing)
  })
  .actions((self) => ({
    fetchThings: flow(function* () {
      // "stuff" is of type "any"!
      const stuff = yield fetchStuff();
      self.things.replace(stuff);
    })
  }));
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 12

toGenerator can be used to convert a promise to a generator yielding that promise. This together with yield* instead of yield (which is made available by setting downlevelIteration to true in the TypeScript compiler options) makes it so the promise return type is retained.

import { flow, types, toGenerator } from "mobx-state-tree";

type Stuff = { id: string; name: string };

function fetchStuff(): Promise<Stuff[]> {
  return new Promise((resolve) => {
    resolve([
      { id: "1", name: "foo" },
      { id: "2", name: "bar" }
    ]);
  });
}

const Thing = types.model({
  id: types.identifier,
  name: types.string
});

const ThingStore = types
  .model({
    things: types.array(Thing)
  })
  .actions((self) => ({
    fetchThings: flow(function* () {
      // "stuff" is now of type "Stuff[]"!
      const stuff = yield* toGenerator(fetchStuff());
      self.things.replace(stuff);
    })
  }));
Run Code Online (Sandbox Code Playgroud)