Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66051158/how-to-use-mobx-state-tree-models-as-function-parameters-with-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...