Optional Chaining Operator in Typescript

馋奶兔 提交于 2021-02-07 04:42:45

问题


In javascript, Optional Chaining Operator is supported by the babel plugin.

But I can't find how to do this in Typescript. Any idea?


回答1:


At time of writing, TypeScript does not support the optional chaining operator. See discussion on the TypeScript issue tracker: https://github.com/Microsoft/TypeScript/issues/16

As a warning, the semantics of this operator are still very much in flux, which is why TypeScript hasn't added it yet. Code written today against the Babel plugin may change behavior in the future without warning, leading to difficult bugs. I generally recommend people to not start using syntax whose behavior hasn't been well-defined yet.




回答2:


Update Oct 15, 2019

Support now exists in typescript@3.7.0-beta

Say thanks to https://stackoverflow.com/a/58221278/6502003 for the update!


Although TypeScript and the community are in favor of this operator, until TC39 solidifies the current proposal (which at the time of this writing is at stage 1) we will have to use alternatives.

There is one alternative which gets close to optional chaining without sacrificing dev tooling: https://github.com/rimeto/ts-optchain

This article chronicles what the creators were able to achieve in trying to mirror the native chaining operator:

  1. Use a syntax that closely mirrors chained property access
  2. Offer a concise expression of a default value when traversal fails
  3. Enable IDE code-completion tools and compile-time path validation

In practice it looks like this:

import { oc } from 'ts-optchain';

// Each of the following pairs are equivalent in result.
oc(x).a();
x && x.a;

oc(x).b.d('Default');
x && x.b && x.b.d || 'Default';

oc(x).c[100].u.v(1234);
x && x.c && x.c[100] && x.c[100].u && x.c[100].u.v || 1234;

Keep in mind that alternatives like this one will likely be unnecessary once the proposal is adopted by TypeScript.

Also, a big thanks to Ryan Cavanaugh for all the work you are doing in advocating this operator to TC39!




回答3:


Typescript 3.7 beta has now support for Optional chaining 👍🎉

You can now write code like this:

let x = foo?.bar?.baz;


来源:https://stackoverflow.com/questions/45843668/optional-chaining-operator-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!