Cannot iterate over mobx-state-tree array using forEach method

Currently, I'm in the process of structuring my new project using TypeScript and MobX-state-tree. However, I've encountered a minor issue while working on it. Specifically, within the service function, I need to loop through the MST array stored in one of my models.

Here is an example of the model in question:

export const ValueHolder = types.model("ValueHolder", {
    identifier: types.maybeNull(types.union(types.number, types.string))
});
    
export const Results = types.model("Results", {
    locations: types.array(ValueHolder)
});

As for the service function:

sendLocationNotification(locations: ValueHolderArrayType) {
    locations.forEach(function (locationResult) {
    });
}

The TypeScript types are defined as follows:

export type ValueHolderArrayType = IArrayType<typeof ValueHolder>;
export type ValueHolderType = Instance<typeof ValueHolder>;

However, I am encountering

TS2339: Property 'forEach' does not exist on type 'ValueHolderArrayType'
.

I have noticed that IArrayType extends from IType, which includes IMSTArray, extending from the root js Array typing, thus implying it should have the forEach signature. Despite my efforts to identify the mistake after thorough research, I still believe the error lies in my typing setup.

If possible, could you provide me with guidance on how to correctly define typings so that I can effectively iterate over the MST array?

Thank you.

Answer №1

Unfortunately, I'm not sure why

export type ValueHolderArrayType = IArrayType<typeof ValueHolder>;
is not functioning correctly since I have never encountered IArrayType before. However, you could specify that locations should be an array of ValueHolderType to make it work:

sendLocationNotification(locations: ValueHolderType[]) {
    locations.forEach(function (locationResult) {
        // ...
    });
}

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

Troubleshooting Vue Unit Tests: Issue with Setting Input Values

I am currently utilizing Vue with typescript and making an effort to perform a unit test on the input value for a login page. The issue lies in the fact that after setting the input value, it does not return as expected – instead, it comes back empty ("" ...

Trouble accessing hyperlink with puppeteer - Thingiverse

Seeking assistance in automating the process of downloading multiple files from Thingiverse. Having trouble locating and clicking on the necessary link for download after selecting a random object. Any help or tips would be greatly appreciated! I have tri ...

What could be causing TypeScript to not locate my custom package?

I decided to create a fork of an existing package and released it with a new, distinct name: https://www.npmjs.com/package/feed-media-fork After tagging a new version, setting up a release on GitHub, and running yarn add feed-media-fork or the equivalent ...

Create an array with individual key-type pairs for each generic element, then iterate through the array

Consider the enum and type declarations in the code below: enum MyEnum { FIRST, SECOND }; type MyType = { firstKey: string | null, secondKey: boolean, thirdKey: MyEnum } Next, a variable is declared using the type as follows: let glob ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

Using TypeORM with a timestamp type column set to default null can lead to an endless loop of migrations being

In my NestJs project using TypeORM, I have the following column definition in an entity: @CreateDateColumn({ nullable: true, type: 'timestamp', default: () => 'NULL', }) public succeededAt?: Date; A migration is gene ...

I'm having some trouble grasping the concept of the useReducer hook

I've been attempting to modify a value from a select menu. My current code is functional, but I'm wondering if switching to useReducer would be more efficient. I made an attempt at it, but unfortunately, I couldn't get it to work. The docume ...

Tips for fixing button display within a list of elements using Angular 2

Looking for a way to display a "copy" button beside each element when the mouse hovers over it on my page that contains multiple lists of elements. Here are a few options I'm considering: Include a hidden button with each element and show it upon ho ...

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

Update the TypeScript definitions in the index.d.ts file using the npm command, by overriding it with the reference types

After running npm install, I noticed that the index.d.ts file contains a reference to the wrong path: /// <reference types="[WrongPath]"/>. As someone new to npm, TypeScript, and web development in general, I'm wondering if it's possible t ...

Typescript Nested Class (also known as Angular Private Inner Interface)

Utilizing a Nested Interface in an Angular Directive When working in Java, I have found static nested classes to be a helpful way to structure my code. Now, when trying to do something similar in Typescript with Angular, I'm running into some challen ...

utilize undefined files are assigned (Typescript, Express, Multer)

I am facing an issue while trying to save image uploads to a folder named "/images". The problem lies in the fact that req.files is appearing as undefined for some reason. Below is the relevant code snippet. Feel free to ask any questions, any assistance w ...

Expanding a Typescript generic class by adding abstract methods

Struggling to expand an abstract generic class and encountering issues with extending certain methods. Take a look at this: abstract class A<T,K> { protected abstract upload<S>(item: T): S protected abstract download(item: T): K } ...

Using TypeScript with makeStyles - how to effectively pass props for styling purposes

Currently, I'm using Material-UI's makeStyles feature in conjunction with TypeScript. After stumbling upon a solution that actually works, here is the snippet of code: export interface StyleProps { md?: any; } const useStyles = makeStyles< ...

The issue of TypeScript failing to return HTML Template Element from Constructor typing is causing complications

There is a restriction on using new to create an instance of Template, which extends an HTMLTemplateElement. To work around this limitation, I fetch and return an HTMLTemplateElement by using document.getElementById(id) within the constructor of the Templ ...

Incorporating lodash in a project with TypeScript and jspm

I seem to be missing something in my setup and would appreciate any assistance. I am working with TypeScript 2 + JSPM. I have tried various configurations in tsconfig using typeRoots and types (including adding the version number in the type name). Despite ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

Testing reactive streams with marble diagrams and functions

Upon returning an object from the Observable, one of its properties is a function. Even after assigning an empty function and emitting the object, the expectation using toBeObservable fails due to a non-deep match. For testing purposes, I am utilizing r ...

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

The term "is" in the output type of a TypeScript function

Within the source code of VSCode, you will find various functions that have a specific return type declaration, such as the following: export function isString(str: any): str is string { if (typeof (str) === _typeof.string || str instanceof String) { ...