Search code examples
typescriptmobx-state-tree

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


I have many lists in my App and I want to create a helper to make a list model, but I can't understand how to correct type it What should I use to define the correct type by model and generic?

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>

this code throws error

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

I need to use type here to IDE suggestions, without it WebStorm talks me that data is any[]


Solution

  • You can specify that the generic type T extends 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)
    };