St1ggy
St1ggy

Reputation: 53

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

Upvotes: 2

Views: 923

Answers (1)

Tholle
Tholle

Reputation: 112807

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)
};

Upvotes: 1

Related Questions