Tips on utilizing MobX State Tree models as function arguments in TypeScript

I am working on creating a helper for my App to generate a list model, but I am struggling with defining the correct type using generics. Can you help me understand how to do it properly?

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>

When running this code, an error is thrown:

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

I want to use proper typing for better IDE suggestions and prevent any errors like WebStorm indicating that data is any[]

Answer №1

If you want to set the condition that the placeholder type T should be of type 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)
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering build errors while utilizing strict mode in tsconfig for Spring-Flo, JointJS, and CodeMirror

While running ng serve with strict mode enabled in the tsconfig.json, Spring-Flow dependencies are causing errors related to code-mirror and Model. https://i.sstatic.net/KUBWE.png Any suggestions on how to resolve this issue? ...

Creating both Uniform and Varying drawings on a single webGL canvas

My goal is to create this specific illustration. https://i.sstatic.net/5AfdW.png This project requires the usage of TypeScript. The Code: The code is organized across multiple files. Within the scenegraph file, there's a function that visits a gro ...

Separate the generic function interface into its own type/interface variable

Below is an example of TypeScript generics that I found on typescriptlang. function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) { return obj[key]; } let x = { a: 1, b: 2, c: 3, d: 4 }; getProperty(x, "a"); getProperty ...

Exploring the capabilities of extending angular components through multiple inheritance

Two base classes are defined as follows: export class EmployeeSearch(){ constructor( public employeeService: EmployeeService, public mobileFormatPipe: MobileFormatPipe ) searchEmployeeById(); searchEmployeeByName(); } ...

The variable 'minSum' is being referenced before having a value set to it

const arrSort: number[] = arr.sort(); let minSum: number = 0; arrSort.forEach((a, b) => { if(b > 0){ minSum += minSum + a; console.log(b) } }) console.log(minSum); Even though 'minSum' is defined at the top, TypeScript still throws ...

The raw password value must be provided and cannot be left blank

I am currently learning Java Springboot and working on creating a todo app with React (TypeScript) and Springboot. As I attempt to signup, an error occurs stating "rawPassword cannot be null" from Springboot. My frontend is running on localhost:3000 and b ...

Instead of displaying the name, HTML reveals the ID

I have defined a status enum with different values such as Draft, Publish, OnHold, and Completed. export enum status { Draft = 1, Publish = 2, OnHold = 3, Completed = 4 } In my TypeScript file, I set the courseStatus variable to have a de ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

The NullInjectorError has occurred due to the absence of a provider for the InjectionToken angularfire2.app

I am currently working on inserting form data into a Cloud Firestore database. Below is my x.component.ts file where I encountered an error in the constructor section: private firestore: AngularFireStore import { Component, OnInit } from '@angula ...

The combination of Angular's ngrx and Router.Events within Rxjs does not seem to function as intended

I'm facing a challenging problem that I can't seem to resolve: onSelectCompany() { combineLatest([this.idCompany$, this.idUser$, this.router.events]).subscribe(res => { if(res[2] instanceOf NavigationEnd){ this.router.navigateByUrl(`g ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Eliminating an element from an object containing nested arrays

Greetings, I am currently working with an object structured like the following: var obj= { _id: string; name: string; loc: [{ locname: string; locId: string; locadd: [{ st: string; zip: str ...

What is the process for creating a personalized tag?

Having created a component similar to the one below. In MyButton.tsx import React from 'react'; import { Button } from '@material-ui/core'; import { Theme, makeStyles, createStyles } from "@material-ui/core/styles"; interface IMyButt ...

What could be causing the rapid breakage of the socket in Ionic 3's Bluetooth Serial after just a short period

Although the code appears to be functioning correctly, it loses connection shortly after establishing it. This snippet contains the relevant code: import { Component } from '@angular/core'; import { Platform, NavController, ToastController, Ref ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

The initial values of Typescript class members are merged directly into the class constructor

This issue has been well documented (check out Initializing variables inline during declaration vs in the constructor in Angular with TS on SO for reference), but it can lead to challenging memory problems. Take a look at the example below class Bar { ...

Discover the process of changing a prop with a button click in NextJS

In my NextJs project, I have a video player component that displays videos using a {videoLink} prop: <ReactPlayer playing={true} controls={true} muted={true} loop={true} width="100" height="100" url={videoLinkDeep} poster="ima ...

How can I determine the existence of an S3 bucket and, if it doesn't exist, create it using TypeScript CDK?

I am currently facing an issue where I need to verify the existence of a bucket in the account and either create a new one if it doesn't exist or use the existing bucket My attempt at achieving this is as follows: import {Bucket} from 'aws-cdk-l ...

The primeng MenuItem component does not have a 'command' property and is of type 'never'

I am currently working on implementing a primeng ContextMenu using the Menu Model API. Within the MenuItem object, there is a property named "command" which, to my understanding, should be a function. As I am receiving the available context menu items fro ...