Difficulty encountered when combining create-react-app with typescript and immutable.js

After realizing that create-react-app now supports typescript, I encountered some issues while trying to transfer my current codebase from react-scripts-ts. Most of my classes are based on Record and cannot be constructed anymore due to errors like:

Cannot set on an immutable record.
I stumbled upon an old Babel issue with a similar problem but couldn't find any guidance on how to configure Babel to fix it. How can I resolve this?

I implement Immutable.js as explained here, for example:

import { Record } from 'immutable'

interface PersonProps {
  firstName: string
  lastName: string
}

const defaultPersonProps: PersonProps = {
  firstName: '',
  lastName: '',
}

class Person extends Record(defaultPersonProps) implements PersonProps {
  public readonly firstName!: string
  public readonly lastName!: string

  public constructor(values: PersonProps) {
    super(values)
  }
}

Check out the related issue on GitHub

Answer №1

In my opinion, the best approach to resolving this issue would be by incorporating "@babel/plugin-proposal-class-properties" with the "loose: false" parameter to prevent assignment (refer to the babel documentation on assignment versus definition: https://babeljs.io/docs/en/babel-plugin-proposal-class-properties#via-babelrc-recommended-). This will utilize Object.defineProperty instead. Immutable.Record does not support assignment.

Here is a simple example I created using create-react-app --typescript. By ejecting create-react-app, I was able to quickly test the "loose: false" option and confirm its functionality (check the babel section of package.json): https://github.com/kimulus/typescriptimmutablerecord

Answer №2

If you haven't tested this code yet, would refactoring it in the following way make a difference?

import { Record } from 'immutable'

interface PeopleProps {
  firstName: string
  lastName: string
}

const personRecord = Record({
  firstName: '',
  lastName: '',
});

class Person extends personRecord implements PeopleProps {
  public readonly firstName!: string
  public readonly lastName!: string

  public constructor(info: PeopleProps) {
    super(info)
  }
}

Answer №3

To achieve immutability, I made the decision to rewrite my code by substituting the usage of "!" with Readonly<PersonProps> instead of using just PersonProps, allowing me to receive type hints for preserving object state.

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

Leverage Webpack to bundle ES Modules with TypeScript module aliases

Hello there, I recently created an npm module using Typescript and ES-modules. Inside the /source folder, you can find my tsconfig.json file which includes a path alias. { "compilerOptions": { "moduleResolution": "Node ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Angular - The filter method cannot be used on Observables

I have a database with users who need to complete unique homework sessions. Each homework session has its own identifier, name, date, and other details. After fetching all the user's homework from the database, it is stored in a private variable call ...

Finding the file path to a module in a NextJS application has proven to be a challenge when utilizing the module

Currently, I am utilizing the webpack plugin module-federation/nextjs-mf, which enables us to work with a micro-frontend architecture. Based on the official documentation and referencing this particular example, it is possible to share components between ...

How can I create a join for my initial column in TypeORM?

I am trying to figure out how to create a verification email for my users, but I'm having trouble understanding how to connect the UserToken table with the user's id in TypeORM. Can someone provide some guidance on this? @Entity({name: "use ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

Steps to receive the "Welcome to React" web page upon executing the `create-react-app` demonstration?

My goal is to set up create-react-app using npm version 6.4.1 I followed these steps: first, I ran npm install --global create-react-app. Then, I executed create-react-app myApp, and entered the myApp folder to run npm start. Compiled successfully! You ...

Tips for sorting through aggregated information in Foundry Functions

How can I filter on grouped data in Foundry Functions after grouping and aggregating my data? See the code snippet below for reference: @Function() public async grouping(lowerBound : Integer ): Promise<TwoDimensionalAggregation<string>> { ...

The reactivity of arrays in Vue components' props is limited

I've got an array with component data that I'm attempting to render using v-for <div :style="style" class="editor-component" v-for="(component, index) in components"> <Component :is="component.name" v-bind="component.o ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Is there a way to prevent Angular component lifecycle hooks like ngOnInit/ngOnDestroy from being triggered when nested within one another?

I am currently developing an application with a page structure that resembles the following: Displaying Objects retrieved from Firestore (similar to Instagram posts) Loading Comments (using the object's id to display comments sub-collection) Load ...

Tips for defining a function across a Angular project

I have the following configuration set up in an Angular5 project using Angular-cli 1.5 within typings.d.ts declare interface String { toSentenceCase(): string; } declare function _debug(o, message?, type?): void; inside app/core/common.ts String.pro ...

IE11 is throwing a fit because of a pesky long-running script error caused by the powerful combination of Webpack, React,

Utilizing webpack 4.* for bundling my react 16.* and typescript 3.* project has been causing issues on internet explorer 11. I consistently encounter a "not responding long running script error" on both local and test servers (in production mode). The lac ...

Async function is improperly updating the array state by overwriting it completely instead of just updating one item as

I am working on a file upload feature where each uploaded file should have a progress bar that updates as the file gets uploaded. I'm using a state to keep track of selected files and their respective progress: interface IFiles { file: File; c ...

Only pass props to `Image` if they have a defined value

As I construct a blog platform using MDX and NextJS, I am creating a custom image component that utilizes the Next <Image> component. However, I've encountered a minor issue for which I have been unable to find a solution. The main question is: ...

Stopping the infinite refresh issue in your React webpack application

Every time I modify the TS file, Webpack keeps refreshing the page without stopping. The console message reads: "@ebpack 5.66.0 compiled successfully" I've searched online and experimented with various plugins, but none of them seem to solve the issu ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

Typescript defines types for parameters used in callbacks for an event bus

Encountering a TypeScript error with our custom event bus: TS2345: Argument of type 'unknown' is not assignable to parameter of type 'AccountInfo | undefined'. Type 'unknown The event bus utilizes unknown[] as an argument for ca ...

"Implementing an abstract method in a class by overloading it with a generic type that

// Greetings from the TypeScript Playground, a platform where you can experiment with TypeScript code. type Constructor<T> = new (...args: any[]) => T; class ServiceChecklistResponse { } class AnotherModel { } abstract class AbstractView { ...