Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - Using optional chaining operator for object property access

TypeScript 3.7 now supports the optional chaining operator. Hence, you can write code such as:

const value = a?.b?.c;

I.e., you can use this operator to access properties of an object, where the object itself may be null or undefined. Now what I would like to do is basically the same, but the property names are dynamic:

const value = a?[b]?.c;

However, there I get a syntax error:

error TS1005: ':' expected.

What am I doing wrong here? Is this even possible?

PS: The proposal seems to imply that this is not possible ?? (but maybe I get the syntax examples wrong).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When accessing a property using bracket notation and optional chaining, you need to use a dot in addition to the brackets:

const value = a?.[b]?.c;

This is the syntax that was adopted by the TC39 proposal, because otherwise it's hard for the parser to figure out if this ? is part of a ternary expression or part of optional chaining.

The way I think about it: the symbol for optional chaining isn't ?, it's ?.. If you're doing optional chaining, you'll always be using both characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...