【问题标题】:How to use MobX State Tree models as function parameters with TypeScript?如何使用 MobX 状态树模型作为 TypeScript 的函数参数?
【发布时间】:2021-05-09 01:55:14
【问题描述】:

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

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[]

【问题讨论】:

    标签: typescript mobx-state-tree


    【解决方案1】:

    您可以指定泛型类型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)
    };
    

    【讨论】:

    • 谢谢,现在 TypeScript 和 IDE 知道我在 createListInterface 中传递了什么
    猜你喜欢
    • 2021-05-03
    • 2019-02-12
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多