我在 React 应用程序中使用带有 Typescript 的 mobx-state-tree。而且,我在使用 Typescript 时遇到了问题,它提示 mobx 类型的类型 types.safeReference
.看起来像safeReference
的类型当您使用 .create()
时,模型定义与其类型不同实际创建模型的实例。在我的代码中,selectedProduct
的类型转换为 string | number | undefined | null
在 productStore
,但在模型定义中是 IStateTreeNode<...> | undefined | null
这就是为什么我在我的根存储中出现错误的原因。我该如何解决?
这是我的产品商店:
import { types } from "mobx-state-tree";
const Product = types.model("Product", {
id: types.identifier,
name: types.string
})
const ProductStore = types
.model("ProductStore", {
products: types.array(Product),
selectedProduct: types.safeReference(Product),
})
.actions((self) => ({
// actions here
}));
export const productStore = ProductStore.create({
products: [],
selectedProduct: undefined // the type here is different from the type in the actual model
});
而且,这是我的根存储:import { types } from "mobx-state-tree";
import ProductStore, { productStore } from "./product-store";
const RootStore = types.model('RootStore', {
productStore: ProductStore
})
export const rootStore = RootStore.create({
productStore: productStore // Here is where I get the typescript error.
});
更新:重现此问题的另一种方法是尝试创建自定义引用。 getter 会提示
undefined
不能分配到类型 {...}。const ProductByIdReference = types.maybeNull(
types.reference(Product, {
get(id: number, parent: Instance<typeof ProductStore>) {
return parent.products.find(p => p.id === id) || undefined
},
set(value: Instance<typeof Product>) {
return value.id
}
})
)
最佳答案
一般来说,当您尝试使用通常使用实例的快照时,您可以使用 cast
.当您尝试使用通常使用快照的实例时,您可以使用 castToSnapshot
.
export const rootStore = RootStore.create({
productStore: castToSnapshot(productStore)
});
关于reactjs - Mobx 状态树引用类型和 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65958595/