如何使用 MobX 状态树模型作为 TypeScript 的函数参数?

How to use MobX State Tree models as function parameters with TypeScript?

我的应用程序中有很多列表,我想创建一个帮助程序来制作列表模型,但我不明白如何正确输入它 我应该使用什么来按模型和泛型定义正确的类型?

const createListInterface = <T>(Model: T) => {
  const initialState = {
    data: types.array(Model),
    isLoading: false,
    isLoadingMore: false,
    isListEnd: false,
  }

  return types.model(initialState)
}

const stateExample = {
  disputesList: createListInterface<Dispute>(DisputeModel),
}

// types

export const DisputeModel = model({
  disputeId: types.number,
  winnerId: types.maybeNull(types.number),
  creatorId: types.number,
  reason: types.string,
  time: types.string,
  status: DisputeStatusEnumModel,
})

export type Dispute = Instance<typeof DisputeModel>

此代码抛出错误

TS2345: Argument of type 'T' is not assignable to parameter of type 'IAnyType'.

我需要在这里使用 type 来 IDE 建议,没有它 WebStorm 告诉我数据是 any[]

您可以指定泛型类型 T 扩展 IAnyType.

const createListInterface = <T extends IAnyType>(Model: T) => {
  const initialState = {
    data: types.array(Model),
    isLoading: false,
    isLoadingMore: false,
    isListEnd: false
  };

  return types.model(initialState);
};

const stateExample = {
  disputesList: createListInterface(DisputeModel)
};