etu*_*dor 4 typescript tslint mobx mobx-react mobx-state-tree
我有这个基本模型。
const stuff = types.model({
term: types.string,
excludeTerm: types.string,
stores: types.array(types.string)
}).actions(self => ({
setTerm(term: string) {
self.term = term
},
setExcludeTerm(term: string) {
self.excludeTerm = term
},
setStores(stores: string[]) {
self.stores = stores // <<< the lint error is on this line
}
}))
Run Code Online (Sandbox Code Playgroud)
我收到以下TS Lint错误:
Type 'string[]' is not assignable to type 'IMSTArray<ISimpleType<string>> & IStateTreeNode<IArrayType<ISimpleType<string>>>'.
Type 'string[]' is missing the following properties from type 'IMSTArray<ISimpleType<string>>': spliceWithArray, observe, intercept, clear, and 4 more.ts(2322)
这是一个令人讨厌的错误。我可以这样分配来修复它:(self as any).stores = stores但是我想停止对我的代码进行黑客攻击。
问题是为什么我会收到此错误?还有另一种在mobx-state-tree中分配数组类型的方法吗?
我在mobx-state-tree中找不到用于处理数组的更详细的文档资料。有人知道吗?
您可以使用self.stores.replace(stores)
这是 MST 的文档,这些确实是我见过的唯一文档: https: //github.com/mobxjs/mobx-state-tree
还有一个功能setLivelinessCheck('error')可以帮助您在本地进行调试以查看可能发生的错误。它位于 API 概述函数列表中:https://github.com/mobxjs/mobx-state-tree#api-overview
解决的办法是使用cast:
import { cast } from "mobx-state-tree"
// .....
self.stores = cast(stores)
Run Code Online (Sandbox Code Playgroud)
这是因为MST可以将快照分配给实际值,并自动将其转换。这不仅适用于数组,还适用于所有类型的值。但是,打字稿不支持将分配范围缩小到比分配给它更窄的范围,这就是需要强制转换的原因。cast不会执行任何操作,但是可以帮助TS确定此分配有效
| 归档时间: |
|
| 查看次数: |
1300 次 |
| 最近记录: |