微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用打字稿正确编写 getParent

如何解决如何使用打字稿正确编写 getParent

所以我有两个模型:RootStoreProjectsModel

const RootStore = types
  .model({
    user: types.maybeNull(User),projects: ProjectsModel,})

ProjectsModel 中,我有一个需要 root 用户属性的操作

const ProjectsModel = types
  .model({...})
  .actions((self) => ({
    loadStarred: flow(function* () {
      const u = getParent(self).user;      < here
      //....

我正在使用 TS 而 TS 不喜欢它:

Property 'user' does not exist on type '(object & IStateTreeNode<IAnyComplexType>) | IStateTreeNode<IAnyStateTreeNode>'.

好吧,我想我需要输入 getParent?

const u = getParent<Instance<typeof RootStore>>(self).user;

哦不,它更不喜欢它

'ProjectsModel' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
'RootStore' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

自参考在哪里?如何正确键入 getParent?

解决方法

我认为你只需要在那里使用 <typeof RootStore>

import { types,getParent } from 'mobx-state-tree';

const ProjectsModel = types
  .model({
    something: types.string
  })
  .actions((self) => ({
    loadStarred: () => {
      const { user } = getParent<typeof RootStore>(self);

      // typed as User,no errors
      console.log(user?.name);
    }
  }));

const User = types.model({
  name: types.string
});

const RootStore = types.model({
  user: types.maybeNull(User),projects: ProjectsModel
});

,

这是由于循环引用而发生的。打破这个并试图跳过这个问题的一种方法是

./root.ts
const RootStore = types
  .model({
    user: types.maybeNull(User),projects: ProjectsModel,})

./iRoot.ts
export type IRootStore = Instance<typeof RootStore>

./projects.ts
const ProjectsModel = types
  .model({...})
  .actions((self) => ({
    loadStarred: flow(function* () {
      const u = getParent<IRootStore>(self).user;      < here
      //....

也有手动创建界面的方法,如下所示:

./root.ts
const RootStore = types
  .model({
    user: types.maybeNull(User),})

./type.ts
export interface IRootStore {    
  user: IUser | null,projects: IProjectsModel,}

./projects.ts
const ProjectsModel = types
  .model({...})
  .actions((self) => ({
    loadStarred: flow(function* () {
      const u = getParent<IRootStore>(self).user;      < here
      //....

我不喜欢这种方法,因为它需要开发人员保持商店和界面同步。

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