MobX存储的TypeScript递归引用

问题描述

我有一个TypeScript递归引用问题。我花了两天的时间来解决这个问题,确实需要一些帮助。

我使用MobX,并且有一个父存储和两个子存储。以下是我的设置概述。注意我如何将母店传递给子店。 (Example App

// ChartWidget.store.ts
const ChartWidgetStore = (dashboardPageStore: IDashboardPageStore) => observable({ /*...*/ });

// TableWidget.store.ts
const TableWidgetStore = (dashboardPageStore: IDashboardPageStore) => observable({ /*...*/ });

// DashboardPageStore.store.ts
export const DashboardPageStore = () => {
  const store = observable({
    chartWidgetStore = null,tableWidgetStore = null,});

  store.chartWidgetStore = ChartWidgetStore(store);
  store.tableWidgetStore = TableWidgetStore(store);

  return store;
};

export interface IDashboardPageStore extends ReturnType<typeof DashboardPageStore> {}

如果我给孩子/小工具商店输入类型:

chartWidgetStore: null as IChartWidgetStore,tableWidgetStore: null as ITableWidgetStore,

我得到错误Type 'IDashboardPageStore' recursively references itself as a base type.(2310),我的所有类型都变成any。我认为它们之所以成为any,是因为ReturnType类型与递归引用相混淆。

enter image description here

这里是Example App

解决方法

  • IChartWidgetStore用于DashboardPageStore的属性
  • DashboardPageStore用于导出IDashboardPageStore的类型
  • IDashboardPageStore用于键入ChartWidgetStore的自变量
  • ChartWidgetStore用于派生类型IChartWidgetStore ...,现在我们来圈了。

如果孩子依靠父母,那么父母就不能依靠孩子,反之亦然。