Answer a question

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.

Answers

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.

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐