如何解决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);
})
}));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。