Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript optional chaining error: Expression expected.ts(1109)

I am trying to do optional chaining in Typescript + React Native.

Let's say I have the following interfaces:

interface Bar {   y: number }  interface Foo {   x?: Bar } 

and I try to run the following:

 const test: Foo = {x: {y: 3}};  console.log(test.x?.y); 

VSCode will show an error under the ?. saying the following: Expression expected.ts(1109)

Do you have any idea why this is happening or how should I fix it? Thanks.

like image 914
Toma Radu-Petrescu Avatar asked Feb 09 '19 22:02

Toma Radu-Petrescu


2 Answers

TypeScript 3.7 has been released, but the stable VS Code uses an older version.

Try + Shift + p and choosing Select TypeScript Version. If it's not 3.7+, that's the issue. The easiest fix is to install the ms-vscode.vscode-typescript-next extension. It'll provide a nightly TypeScript version for VS Code to use (May require restarting VS Code FYI).

You'll want to remember to remove the extension when VS Code gets TypeScript 3.7+ by default.

See https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions for more details.

like image 61
Austin Avatar answered Sep 19 '22 19:09

Austin


For those who are wondering, optional chaining (the ? operator) is now available on TypeScript 3.7 (Beta), as of October 2019. You may install that version by running the following command:

npm install typescript@beta 

This is how you may use the operator, as explained on the release notes.

let x = foo?.bar.baz(); 

Which is equivalent to

let x = (foo === null || foo === undefined) ?     undefined :     foo.bar.baz(); 

Apart from Optional Chaining, other interesting features include Nullish Coalescing (the ?? operator).

Update (November 2019)

TypeScript's optional chaining is now officially available. Installing the latest version of typescript should allow you to access the cool new features.

npm install typescript 

For those who are using VS Code, please refer to Austin's excellent answer on getting it to work with the new TypeScript version.

For those who are working with WebStorm, you will need to configure TypeScript to use your project's installed TypeScript version.

Preferences -> Languages & Frameworks -> TypeScript 

In addition, if you are using an older version of WebStorm, you may face an error/warning when you try to use the Nullish Coaslescing operator (??). To fix this, you will need to install WebStorm 2019.2.4, or any version that is newer than the above.

like image 27
wentjun Avatar answered Sep 17 '22 19:09

wentjun