typescript - Mobx-State-Tree - 分配给数组类型

标签 typescript mobx tslint 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
  }
}))

我收到以下 TS Lint 错误:

Type 'string[]' is not assignable to type 'IMSTArray<ISimpleType> & IStateTreeNode<IArrayType<ISimpleType>>'. Type 'string[]' is missing the following properties from type 'IMSTArray<ISimpleType>': spliceWithArray, observe, intercept, clear, and 4 more.ts(2322)

这是一个烦人的错误。我可以通过这样分配来修复它:(self as any).stores = stores 但我想停止对我的代码进行 hack。

问题是为什么我会收到这个错误?在 mobx-state-tree 中是否有另一种分配给数组类型的方法?

我在 mobx-state-tree 中找不到更详细的数组处理文档。有人知道吗?

最佳答案

解决方案是使用cast :

import { cast } from "mobx-state-tree"

// .....

self.stores = cast(stores)

这是因为 MST 允许将快照分配给实际值,并自动转换它们。这不仅适用于数组,还适用于所有类型的值。但是, typescript 不支持分配比分配给它的东西更窄的分配,这就是需要强制转换的原因。 cast 没有做任何事情,但是它帮助 TS 判断这个赋值是有效的

关于typescript - Mobx-State-Tree - 分配给数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55689302/

相关文章:

angular - @ngx-translate Nativescript/Angular 应用程序

reactjs - 'Element[]' 类型的参数不能分配给 'Element' 类型的参数

javascript - 无状态函数组件不能被赋予 refs

angular - "ng lint"安静选项?

angular - 如何在 angular cli 中忽略/排除某些文件/目录

javascript - @typescript-eslint/eslint-插件错误 : 'Route' is defined but never used (no-unused-vars)

typescript - 条件类型无法识别所有输入都会导致相同的条件结果

javascript - Reactjs typescript : Property 'toLowerCase' does not exist on type 'never'

javascript - 为什么 mobx 不是 @computed 值?

javascript - 未找到从 mobx 导入可观察的内容或其他内容