Mobx状态树参考类型和打字稿

阿塔拉瓦蒂

我在React应用程序中使用带有Typescript的mobx-state-tree。而且,我在Typescript上遇到问题,它抱怨mobx type的类型types.safeReferencesafeReference当您.create()实际用于创建模型实例时,模型定义中的类型看起来与它的类型不同在我的代码中,selectedProduct的类型被转换为string | number | undefined | nullin 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.
});

更新:

重现此问题的另一种方法是尝试创建自定义引用。吸气剂将抱怨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)
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章