Mobx-State-Tree - Implementing Assignment for Arrays

I have a simple model that I am working with.

const info = types.model({
  name: types.string,
  age: types.number,
  hobbies: types.array(types.string)
}).actions(self => ({
  setName(name: string) {
    self.name = name
  },
  setAge(age: number) {
    self.age = age
  },
  setHobbies(hobbies: string[]) {
    self.hobbies = hobbies   // <<< the lint error is on this line
  }
}))

When trying to assign an array, I encounter the following TS Lint error:

Type 'string[]' is not assignable to type 'IMSTArray<ISimpleType> & IStateTreeNode<IArrayType<ISimpleType>>'. Type 'string[]' is missing the following properties from type 'IMSTArray<ISimpleType>': spliceWithArray, observe, intercept, clear, and 4 more.ts(2322)

This error is frustrating. Although I can work around it by using (self as any).hobbies = hobbies, I am looking for a cleaner solution to address this issue.

I am wondering why exactly this error occurs and if there is a proper method to assign values to an array type in mobx-state-tree?

I have searched for more detailed documentation on handling arrays in mobx-state-tree but haven't found anything thorough. Does anyone have insights or resources on this topic?

Answer №1

To resolve this issue, utilize the cast function:

import { cast } from "mobx-state-tree"

// .....

self.stores = cast(stores)

The reason for using `cast` is that MST allows snapshots to be assigned to real values and automatically converts them. This process applies to all types of values, not just arrays. TypeScript lacks support for assigning a value that is more narrow than the type it is being assigned to, hence the need for `cast`. Although `cast` itself doesn't perform any actions, it helps TypeScript recognize the validity of this assignment.

Answer №2

To update the stores, you can utilize the method self.stores.replace(stores)

If you're looking for documentation on MST, check out the following link which seems to be the most comprehensive: https://github.com/mobxjs/mobx-state-tree

For easier debugging locally, you can use the function setLivelinessCheck('error'). This function can help catch and display errors effectively. It is listed under the API Overview functions: https://github.com/mobxjs/mobx-state-tree#api-overview

Answer №3

The data structure used for arrays in MST is not your typical array; it's actually a complex type -

IMSTArray<ISimpleType<string>>
. Therefore, the TypeScript lint error you received should come as no surprise. However, I must admit that it can be quite daunting for newcomers.

Your solution to this issue may seem like a workaround, but in reality, it is the simplest way to deal with it.

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

The SpinButton object has an undefined public property called 'value' and the public method 'focus()' is not available

Recently, I've delved into using reactjs, typescript, and Office UI Fabric. However, I'm facing a challenge with one of the components from fabric. In this scenario, I have a simple Product component containing a SpinButton and a DefaultButton. M ...

Encountered an issue while trying to install the package '@angular/cli'

Encountered errors while attempting to install @angular/cli using npm install -g @angular/cli. The node and npm versions on my system are as follows: C:\WINDOWS\system32>node -v v 12.4.0 C:\WINDOWS\system32>npm -v 'C ...

Is it possible to efficiently structure intricate JSON data onto interfaces in TypeScript with the incorporation of observables?

I am currently working on creating a simple web news reader that relies heavily on the Google News API (). I have set up all the necessary services, models, etc. However, I am having difficulty mapping the data onto specific interfaces. The Google API retu ...

Strategies for implementing recursive component calling while maintaining nested level monitoring in React Native

Within my application, I have two key components: CommentList and Comment. The CommentList component is responsible for rendering comments by calling the Comment component through a map function, which loops ten times. A unique feature of my app is that e ...

What is the best approach to manage the package versions of react, react-dom, @types/react, and @types/react-dom?

Recently, I decided to update the versions of react/react-dom in my project from 16.3.2 to 16.8.6 so that I could start using hooks. Surprisingly, after making some minor adjustments to my code, the update went smoothly. However, since we are utilizing ty ...

Having trouble with the service connection in Stackblitz?

Objective: I am trying to establish a connection with the Data service in StackBlitz. Issue: Unfortunately, my attempts are not successful. Can anyone pinpoint what I am overlooking? Project Link: https://stackblitz.com/edit/angular-mpy6pr Many th ...

Error in Angular 8 Pipe: Variable remains undefined outside of Subscription

How can I access a variable inside a subscription in an angular pipe to return the transformed value? What I attempted transform(value: any, ...args: any[]): any { const clientKey = args[0]; let arr = []; let newValue; this.dbJobs.getJobsFromK ...

Determining the data type of a generic variable within an Angular component

I'm currently in the process of developing a versatile component that can handle data of only two specific types: interface X{ name: string, path: string, type: string, } interface Y{ name: string, path: string, } Both types X a ...

How to create an array of objects in TypeScript

I am looking to define an array of objects in TypeScript. Here is my example: const a = [{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8, }, { name: 1, age: 2, car1: 8, car2: 8, ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Jest ran into a surprising token related to NUXT typescript

After spending two days searching and trying various solutions without success, I am reaching out for help. Can anyone provide a clue? Below are the configuration files I am using. Any assistance would be greatly appreciated. jest.config.js .babelrc .babe ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...

Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output: for (let i = 0; i < this.arrayNumberOne[0].length; i++) { let orangeOne = this.a ...

Error overload in the nest.js build process

I've been using my Nest.js app for a while now, but recently encountered an issue when running npm run build. node_modules/@nestjs/config/dist/config.service.d.ts:1:23 - error TS2305: Module '"./types"' has no exported member &apos ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

Tips for retrieving keys of a specific type from an object

If I were to create an interface named Data: interface Data { key1: number key2: boolean set1: SomeInterface[] set2: AnotherInterface[] } Is there a way to retrieve the properties of the interface Data that includes [] in the form of a discriminat ...

Why are nested RxJS map operators used and how do they impact data transformation?

Recently, I enrolled in an online Angular course and discovered that RxJS plays a significant role in web development. While exploring different concepts, I encountered a nested map operator that intrigued me. Although I can somewhat decipher what is happe ...

The Next.js API has a mysterious parameter that remains undefined

I currently have a component implemented import React, { useEffect } from "react"; import styles from "../styles/success.module.css"; import { useRouter } from "next/router"; import axios from "axios"; const Success ...

Building an observable TypeScript class with RXJS: A step-by-step guide

I can't seem to find a solution for making an entire model observable. Despite reading this post, it doesn't quite meet my requirements. I'm not looking to make individual properties observable, but rather the entire class itself. Here' ...

Can a concept like "A Rectangle can be a Square but a Square cannot be a Rectangle" be formulated?

Currently, I am working on developing a unique "loose" nominal type that allows assignment from its base type, but restricts assignment from other nominal types with the same base type. Is there a way to modify the existing Nominal type found here to achie ...