Search code examples
typescriptmobxmobx-state-tree

cannot do forEach on mobx-state-tree array


I am trying to organize my new project using typescript and MobX-state-tree But I`ve faced one small issue In the service function, I need to iterate over the MST array, which is stored in one of my models

Here's an example of this model

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

and my service function

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

Typescript types defined like this

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

But this results in TS2339: Property 'forEach' does not exist on type 'ValueHolderArrayType'.

I can see that IArrayType extended from IType, which contains IMSTArray, which in the root extended from js Array typing, so it should have forEach signature. Apparently, I am doing something wrong, but after studying I just can't find my mistake. I think the error is in my typing.

Could you please guide me on how I should write typings so I would be able to iterate over the MST array?

Thanks


Solution

  • I can sadly not tell you why export type ValueHolderArrayType = IArrayType<typeof ValueHolder>; is not working as I've never explicitly used IArrayType before, but you could annotate locations to be an array of ValueHolderType and it will work:

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