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

Typed yield expression in MobX-State-Tree flow

在 MobX-state-tree (MST) 中执行异步操作的推荐方法是使用 flow,它将生成器函数作为第一个参数,每个 promise 都应该被生成。

yield expressions are of type any in TypeScript,但是有什么方法可以在 MST 中自动键入 yield 表达式吗?

例子

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);
    })
  }));

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) 使得承诺 return 类型得以保留。

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);
    })
  }));