Enhanced assistance for optional chaining operator available in Visual Studio Code

React Native 0.56 now supports the Optional Chaining Operator with ?.

Unfortunately, the latest stable version of VS Code does not recognize this syntax and displays a TypeScript validation error:

[ts] Expression expected.

No compile-time or eslint errors are shown.

How can I resolve this issue?


Updated on 2019/12/11:

Optional chaining is officially supported by TypeScript version 3.7!

If you still encounter this error, it might be because the TypeScript library in your VSCode is below version 3.7.

You can easily fix this by installing a newer version of TypeScript (>= 3.7) as a dev dependency in your workspace (via npm or yarn).

Then, go to the command palette, type tstv, and switch the TypeScript version used for JS and TS features from VS Code's Version to Workspace's Version (ensure it's >= 3.7) and you're all set!

This feature is truly amazing - thank you all and happy coding!

Answer №1

Visual Studio Code version 1.41 has introduced support for optional chaining in JavaScript and TypeScript files. This feature includes syntax highlighting and IntelliSense.

If you are using VS Code 1.41 or later and encounter issues with optional chaining, consider the following troubleshooting steps:

  • Review your installed extensions to ensure they fully support optional chaining, as certain extensions may not recognize this feature causing errors or incorrect syntax highlighting

  • If you have configured a workspace typescript version, verify that it is at least TypeScript 3.7+

Answer №2

To experience the latest features, consider installing JavaScript and TypeScript Nightly from the Visual Studio Marketplace. After installation, remember to restart VSCode.

Answer №3

After troubleshooting, I successfully resolved the issue by disabling js/ts validation in vscode json settings:

"javascript.validate.enable": false

It may be necessary to add eslint-plugin-babel for eslint rules.

{
  "plugins": [
    "babel"
  ],
  "rules": {
    "babel/new-cap": 1,
    "babel/camelcase": 1,
    "babel/no-invalid-this": 1,
    "babel/object-curly-spacing": 1,
    "babel/quotes": 1,
    "babel/semi": 1,
    "babel/no-unused-expressions": 1,
    "babel/valid-typeof": 1
  }
}

Answer №4

Until I removed the extension JavaScript and TypeScript IntelliSense, this issue persisted for me.

If you're still facing the problem, consider uninstalling old plugins. You could also experiment with the vscode insiders version to see if that resolves it. In my case, it worked seamlessly without any additional modifications needed.

Answer №5

To enhance my code, I must include the

"tslint-config-prettier"
in the tslint.json configuration file

This snippet shows part of my tslint.json setup

{
  "defaultSeverity": "error",
  "extends": [
    "tslint:recommended",
    "tslint-config-prettier"  # ----> This line
  ],
  "jsRules": {},
  "rules": {
    "semicolon": false,
    "quotemark": [true, "single"],
    "prefer-for-of": false,
    "object-literal-sort-keys": false,
    "ordered-imports": false,
    "interface-name": false,
    "callable-types": false,
    "no-console": false,
    "no-bitwise": false,
    "variable-name": [
      true,
      "allow-leading-underscore",
      "allow-snake-case"
    ]
  },
  "rulesDirectory": []
}

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

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Error message pops up in WebStorm when attempting to access the map object in Angular

Within one of the services in my Angular application, I have utilized the map() function to retrieve data from the GitHub API. getUser(username: string) { // Regular Expression used for String Manipulation return this.http.get('https://api.github.com ...

Certain information is failing to be added to the list

userSPMSnapshot.forEach((doc) => { console.log(doc.id, "=>", doc.data()); userSPMList.push(userSPM.fromFirestore(doc)); }); console.log(userSPMList) I'm encountering an issue where some fields in my data lose their values when I p ...

Special react-hook designed for dynamically assigning CSS classes

I'm currently exploring React's hooks and playing around with reusing the ability to add a shadow to an element (utilizing bootstrap as the css-framework). Here is the current structure of my App: export const App: React.FunctionComponent<IA ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

Guide to setting up an interface-only project (along with its dependent projects) on NPM

I'm encountering two problems with my TypeScript project. Imagine I have a interface-only TypeScript project called myproject-api. My plan is to implement the interfaces in two separate projects named myproject-impl1 and myroject-impl2. I am utilizin ...

Dynamic Type in Typescript Record

Looking for a way to attach types to record names in a class that returns a Record. The current code snippet is as follows: interface DataInterface { bar: number; foo: string; fooBar: boolean; } export class MyClass { public bar: number; p ...

Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest. W ...

VSCode - when indenting, spaces are added around strings

Currently, I am utilizing Vue 3 along with Prettier in VS Code. One issue I am encountering is that when a string is on its own line, it is formatted correctly to my liking. However, the problem arises when my browser in Dev Tools renders strings with extr ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

The 'job' field is not recognized within the 'PrismaClient' type, please check the documentation for correct usage

Currently, I am utilizing Expressjs as a backend along with Prisma for database management and TypeScript implementation. I have been referencing this specific article in my development process. A type error that I am encountering is stated as Property &a ...

Error message: Duplicate identifier found in Typescript

Encountering an error while trying to run my angular-meteor client (ionic serve), specifically: [00:29:20] typescript: node_modules/meteor-typings/1.3/main.d.ts, line: 657 Duplicate identifier 'Status'. L657: type Status ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

How to defer the rendering of the router-outlet in Angular 2

I am currently working on an Angular 2 application that consists of various components relying on data fetched from the server using the http-service. This data includes user information and roles. Most of my route components encounter errors within their ...

Is there a way to retrieve a specific type from a union-based type by using a generic function in Typescript?

When working with my API, I have noticed a consistent pattern where it returns either a specific type or a TypeScript type called BadResult, as shown below: type Result1 = CreatedPersonResult | BadResult; type Result2 = CreatedRoleResult | BadResult; To s ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Progressive series of observable conditions

The issue at hand: I am faced with the task of checking multiple conditions, some of which lead to the same outcome. Here is the current flow: First, I check if a form is saved locally If it is saved locally, I display text 1 to the user If not saved l ...