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

问题描述

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

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 可用于将承诺转换为产生该承诺的生成器。这与 yield* 而不是 yield(通过设置 downlevelIteration to true in the TypeScript compiler options 使其可用)一起使承诺返回类型得以保留。

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