Error: Expected an expression but found a parsing error in the eslint code

interface Address {
  street: string,
}

export const getAddress = (address: Address | null) : string =>
  address?.street ? `${address?.street}`
    : '0000 Default Dr';

Why am I receiving the error message

Parsing error: Expression expected. eslint
on address in address?.street ?? Any ideas?

Eslint rules are applied to both .js and .ts files:

 {
      "extends": [
        "plugin:cypress/recommended",
        "plugin:@typescript-eslint/recommended"
      ],
      "overrides":
        {
          "files": ["**/*.{ts,tsx}"],
          "parser": "@typescript-eslint/parser",
          "parserOptions": {
            "project": "./tsconfig.json"
          },
          "plugins": ["@typescript-eslint", "prettier", "react-hooks", "jsx-a11y"],
          "extends": [
            "eslint:recommended",
            "react-app",
            "plugin:@typescript-eslint/recommended",
            "plugin:@typescript-eslint/recommended-requiring-type-checking",
            "prettier"
          ],
          "rules": {
            "@typescript-eslint/explicit-function-return-type": "off",
            "@typescript-eslint/no-explicit-any": "off",
            "@typescript-eslint/no-shadow": "off",
            "no-empty-function": 0,
            "@typescript-eslint/no-empty-function": "off",
            "@typescript-eslint/explicit-module-boundary-types": "off",
            "@typescript-eslint/no-non-null-assertion": "off",
            "no-use-before-define": "off",
            "@typescript-eslint/no-use-before-define": ["error"]
          },
          "settings": {
            "import/parsers": {
              "@typescript-eslint/parser": [".ts", ".tsx"]
            },
            "import/resolver": {
              "typescript": {}
            },
            "react": {
              "version": "detect"
            }
          }
        }
      ]
    }

Answer №1

It seems that the ES version is currently at its default setting. The use of optional chaining (address?.street) was introduced in ES2019. By default, ESLint recognizes ECMAScript 5 syntax. To enable ES2019 syntax, simply add the following line to your eslintrc under parserOptions: ecmaVersion: '9' (or '2019') (refer to the documentation).

Answer №2

There are various reasons that can lead to encountering this issue -> link to the informative article

In this scenario, separating the declaration of const and variable export into distinct lines would resolve the problem.

In addition to the insights provided in the aforementioned resource and pertaining to my unique situation, I faced this error when I concatenated statements without utilizing parentheses and included a comment inline at the end.

The original statement triggering the error appeared as follows:

if (selectedHour < startHour - 1) for (let i = 0; i <= 60; i++) elapsedMinutes.push(i); // disable all minutes

To address this, it was necessary to eliminate the comment from the end and relocate it onto its own line:

// disable all minutes
if (selectedHour < startHour - 1) for (let i = 0; i <= 60; i++) elapsedMinutes.push(i);

I trust this solution proves beneficial! Enjoy your coding endeavors!

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

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

An error occurs with webpack during postinstall when trying to load TypeScript

I have created a custom package that includes a postinstall webpack script as specified in my package.json file: "scripts": { ... "postinstall": "webpack" } The webpack configuration looks like this: const path = require('path'); ...

What is the function of the OmitThisParameter in TypeScript when referencing ES5 definitions?

I came across this specific type in the ES5 definitions for TypeScript and was intrigued by its purpose as the description provided seemed quite vague. /** * Removes the 'this' parameter from a function type. */ type OmitThisParameter<T> ...

Declare a new variable with a specific data type in TypeScript

I'm working on creating a variable in my component of a specific type, as shown below. myrequest.model.ts export class MyRequest { public endValue: string; public yearEnd: string; } When importing the above into my component, I do the follow ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

The Intl.DateTime formatter consistently generates incorrect times even after refreshing the component in a React application

Our component is responsible for receiving information from the backend and rendering it. The properties of the component are defined as: interface CitizenshipProps { citizenship?: Citizenship; name?: string; lastName?: string; onUpdateClic ...

What is the process for extracting the elements of an array fetched from a service in Angular 2?

Currently, I am learning Angular 2 + PrimeNG and going through a quick start project available at the following link: https://github.com/primefaces/primeng-quickstart The project is a CRUD application and it functions flawlessly. The data is neatly displa ...

Why is it that when the form is submitted, the value becomes unclear?

This is a form with HTML and TypeScript code that I am working on. <form> <div class="form-group"> <input class="form-control" ([ngModel])="login" placeholder="Login" required> </div> <div class="form-group"> &l ...

An in-depth guide on implementing Highcharts.Tooltip functionality in a TypeScript environment

Currently, I am trying to implement a tooltip activation on click event in Highcharts by following an example from this URL: Highcharts - Show tooltip on points click instead mouseover. The challenge I'm facing is that I am using TypeScript and strugg ...

How to leverage async/await within loops in Node.js for optimized performance and efficiency

Hey there, I'm working on my nodejs api where I need to fetch data inside a loop and then perform another loop to save data in a different table. Can anyone guide me on how to achieve this? Below is a snippet of what I have attempted so far without su ...

What are some ways to specialize a generic class during its creation in TypeScript?

I have a unique class method called continue(). This method takes a callback and returns the same type of value as the given callback. Here's an example: function continue<T>(callback: () => T): T { // ... } Now, I'm creating a clas ...

Can we determine the type signature of useCallback for an event handler by inference?

Currently, I am working with TypeScript and React to implement a callback function using an arrow function on a Material UI <Select> component: import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import ...

Encountering deployment problems with React and TypeScript involving router on Github Pages

After successfully running locally, I encountered a 404 error when deploying the website using "npm run deploy." My application is built with React and TypeScript, utilizing react-router-dom BrowserRouter for navigation between pages. I've spent 7 h ...

Display the React component following a redirect in a Next.js application that utilizes server-side rendering

Just starting out with next.js and encountering a problem that I can't seem to solve. I have some static links that are redirecting to search.tsx under the pages folder. Current behavior: When clicking on any of the links, it waits for the API respo ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

There is a potential for an object to be 'undefined' in TypeScript

My current project involves making a GET request from a mockAPI with the following structure: "usuarios": [ { "nome": "foo bar", "cpf": "213.123.123-45", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Cannot compile Angular 4 Material table: Encountering unexpected closing tag

Currently, I am working on an Angular 4 Project that involves using Material. The main task at hand is to implement a table from Angular Material. However, the issue I am facing is that the table does not compile as expected. Here's the HTML code sni ...

Crafting a model for arrays of objects - a guide to perfection

Why am I experiencing errors in the console when trying to set the API return to a variable? How can this issue be resolved? This is my TypeScript code: public myData = new myDataModel(); getData(){ this.myCoolService.getDataAPI() .subscribe(( ...