Experimental support of Optional Chaining (at least static property access) via experimentalOptionalChaining · Issue #30167 · microsoft/TypeScript (original) (raw)

Suggestion

Add experimentalOptionalChaining property to compilerOptions which will support at least static property access – the most required and expected feature.

Use Cases

For me, in 2019 the most important part of Optional Chaining is static property access. It will greatly improve DX for GraphQL client apps and make client code more robust and clean. 🚀

Current shortcomings:

Examples

Assume we have following GraphQL response from the server on the client side:

interface IResponse { viewer?: { article?: { title?: string } } }

const response: IResponse = await apolloClient.query(query { viewer { article(id: 15) { title } } });

On any level, graphql may return null, so before displaying title we must check viewer and article existence.

... with if-check-hell 🤢

if (response && response.viewer && response.viewer.article && response.viewer.article.title) { // ... display title }

Pros: statically checked (if query changed, then we will be warned about un-existed props)
Cons: to much code

... with unchecked dottedPaths as string 💩

if (_.get(response, ['viewer.article.title'])) { // ... display title }

Pros: quite clean code
Cons: statically UNchecked (if query changed, then we will NOT be warned about un-existed props checks)

... with Optional Chaining ❤️

if (response?.viewer?.article?.title) { // ... display title }

Pros: very clean code & static checks
Cons: not implemented in TS, but already implemented about a year ago in Flow 0.74, Eslint, Babel.

Recap

We just have 3 levels deep query, but in most cases it's deeper.

if (response && response.viewer && response.viewer.article && response.viewer.article.title) { if (_.get(response, ['viewer.article.title'])) { if (response?.viewer?.article?.title) {

Definitely, OptionalChaining is the winner 🥇

Suggestion: repeat once more

Just add static property access from optional chaining proposal under experimentalOptionalChaining flag. This part is stable in the proposal and it is the most required feature in 2019.

Let's keep problematic optional chaining for function calling, short-circuiting, grouping, deletion, template literals – out of the scope of this issue.

Please do not reference this issue as a duplicate for issue #16 from the 2014 year, here are 2019 and requirements changed from that time.

Search Terms

Optional Chaining, null propagation.

Checklist

My suggestion meets these guidelines:

If a miracle will happen 😂

If you like the fact that optional chaining was shaken off the dust from #16 and may even be implemented in the near future – send a SWAG from your company to the following address

050010, Kazakhstan, Almaty,
Kabanbay Batyra 21 apt 3,
Mobile +7707234004
Pavel Chertorogov

or just give a 👍