Implementing optional chaining in your Create React App project when using TypeScript

An issue arose with the usage of the experimental syntax 'optionalChaining' as it is currently not enabled

Encountering the error mentioned above led me to this helpful thread, where I followed the advice to include

"@babel/plugin-proposal-optional-chaining": "^7.7.4"
in my devDependencies.

However, a new error surfaced after making this addition,

To resolve this issue, add @babel/plugin-proposal-optional-chaining () to your Babel configuration's 'plugins' section for transformation to take place.

Following another insightful post, I included a .babelrc file at the root of my project

{
    "presets": ["react", "es2015","stage-1"],
    "plugins": ["transform-runtime", "transform-optional-chaining"]
}

Regrettably, this did not resolve my issue. Upon further investigation, I discovered that Create React App restricts modifications to babel configurations. This prompted me to seek an alternative solution for enabling optional chaining without altering the entire CRA setup.

P.S. My current environment includes "typescript": "^3.7.2" according to my package.json. Although I have executed npm install to ensure the latest version is installed, there may be conflicting versions at play within the CRA setup.


EDIT: Upon inception of the project using CRA, we were utilizing TypeScript: 3.6.x. Seeking to leverage Optional Chaining, I updated my package.json to include "typescript": "^3.7.2" followed by a npm install command. The challenge arises from the discrepancy between the TypeScript version specified and the existing configuration within CRA, leaving me uncertain on how to proceed with updating.

Answer №1

When using Create-React-App, babel is used to transpile TypeScript instead of relying on the npm installed version of TypeScript. The good news is that react-scripts Version 3.3.0 supports TypeScript 3.7. To start using it, simply execute the following command:

  • yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a584f4b495e07594958435a5e596a190419041a">[email protected]</a>

    -or-

  • npm install -s <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedccbcfcdda83ddcddcc7dedaddee9d809d809e">[email protected]</a>

Answer №2

Support for it is available in React scripts 3.3.0 and newer versions. You do not have to install react-scripts@next.

Simply add "react-scripts": "^3.3.0" to your package.json file and it should function correctly.

Answer №3

Package.json

{
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom"
  },
  "devDependencies": {
    "@babel/plugin-proposal-optional-chaining": "^7.2.0",
    "customize-cra": "^0.4.1",
    "react-app-rewired": "^2.1.3"
  }
  ...other
}

Config-overrides.js

const { useBabelRc, override } = require('customize-cra');
module.exports = override(useBabelRc());

.Babelrc

{
  "plugins": ["@babel/plugin-proposal-optional-chaining"]
}

Read more in-depth about this topic here

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

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

Is there a way to retrieve all values in the pathname from a URL after the initial slash

Extracting pathname pathname: "/kids/dlya-malyshey/platya-i-yubki" By using the substr function, I will remove the initial slash location.pathname.substr(1,); Now, the result is kids/dlya-malyshey/platya-i-yubki The challenge is to extract all ...

There is no response when executing the babel command

After installing babel with the command npm install -g babel-cli, I encountered a strange issue. Whenever I tried to run the babel command in either the nodejs cmd (as admin) or my PyCharm editor's terminal, nothing would happen. It seemed like it was ...

Why doesn't DataView or Int32Array interpret underlying bytes as individual integers instead of groups?

I am interested in extracting integers from a byte buffer and accessing them by their specific index. For example, retrieving i[0] would yield the integer value represented by the initial four bytes of the buffer, while i[1] would provide the integer value ...

What is the collection of types that accept a parameterized argument?

I am working with an item interface that looks like this: interface Item<Href extends string> { href: Route<Href> } My goal is to create a component that accepts a list of these Item objects as a single property: interface Props { items: I ...

Form with checkboxes in a Next.js and Typescript application

I am currently working on a project using Next.js and Typescript. I have implemented a form in this project, which is my first experience with Typescript and checkbox types. However, I am encountering difficulties in retrieving all checkbox values, adding ...

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...

Setting up an OR guard in NestJS is a crucial step in managing

I need to secure a controller route using Guards, including IsAuthentifiedGuard, HasRoleGuard, and IsSafeGuard. I want the route to be accessible if at least one of these conditions is met: IsAuthentifiedGuard and HasRoleGuard pass IsSafeGuard passes For ...

Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values. Take this example: export class Foo{ private _bar: string; constructor(pr ...

Accessing the id within both objects is proving to be a challenge for me

I'm facing an issue with accessing and posting values of the id within Position and Department in Angular. It seems like the id is not being accessed correctly. addEmployee.model.ts export class AddEmployee { Position: { id: string; }; De ...

A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be: obj = { a: 'xxx', b: 'x ...

Transforming Form Field Inputs into Model Data Types

Looking at my Angular 8 component, there is a form that allows users to create a post. The PostModel consists of three properties: a string, a boolean, and a number: export interface PostModel { title: string year: number; approved: Boolean; } T ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

Unable to analyze parameters provided to a simulated object in Jest

I have a relatively simple Typescript class and method that I want to test using Jest. The goal is to mock out the dependencies of this method: import {DynamoWorkflow} from '..'; import {Injectable} from '@nestjs/common'; @Injectable() ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

What are the most effective techniques for utilizing promise.all in your codebase?

When trying to consolidate responses from two API calls in the code below, I'm facing an issue where Promise.all is not being invoked. Any suggestions on what might be implemented incorrectly and the best practice to achieve this using Promise.all? T ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

"NODEJS: Exploring the Concept of Key-Value Pairs in Object

I am facing a challenge with accessing nested key/value pairs in an object received through a webhook. The object in req.body looks like this: {"appId":"7HPEPVBTZGDCP","merchants":{"6RDH804A896K1":[{"objectId&qu ...

A Typescript interface fails to validate a dynamic object if it does not include required keys

Looking for a way to incorporate an interface for this array of objects that is being passed as a prop. const playersData = [ { id: 1, // Will always be a number (provided by user) extraNode: <ExampleComponent />, // Optional Reac ...

Typescript Vue Plugin

I am currently working on developing a Vue logger plugin export default new (class CustomLogger { public install(Vue: any) { Vue.prototype.$log = this; } error(text: string) { console.log(text) } })(); This code is located in main.ts f ...