Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 3.7@beta Optional Chaining operator using problem

I'm trying typescript optional chaining operator but throwed this exception.

index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. 

My sample code has below

const url = URI({     protocol: 'http',     hostname: 'example.org'  })  // This line throwed document.getElementById('output')?.innerHTML = url.toString() 

How to resolve this problem?

like image 445
muratoner Avatar asked Oct 16 '19 13:10

muratoner


People also ask

Does TypeScript support optional chaining?

Optional chaining is not a feature specific to TypeScript.

How do I enable optional chaining?

To enable optional chaining, you need to install a package. At the time of writing, optional chaining is not natively supported in Javascript, it is a new feature introduced in ES2020. Until it is fully adopted we can get all the optional goodness by installing a package!

Can I use optional chaining (?

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

Which node version has optional chaining?

Optional chaining is currently not supported in Node. js version 13 and below. It will be supported from Node. js version 14 and most of the browsers as it is moved to Stage 4.


2 Answers

objectVariableName!.propertyName = 'some value to assign'; 

Please note the exclamation symbol i.e,!

like image 114
Nitin Jha Avatar answered Sep 24 '22 08:09

Nitin Jha


const output = document.getElementById('output'); if (output) output.innerHTML = url.toString() 

This operator is made for accessing deep nest values.

Let's look at document.getElementById('output')?.innerHTML. This will return undefined (if '#output' not exists) or string (if '#output' exists). And you trying to assign string to it.

Here you are trying to set a new value for an object property that may not exist.

So yep, optional property access can not be used at the left-hand side of an assignment.

You can read more about it in proposal

like image 40
iamolegga Avatar answered Sep 20 '22 08:09

iamolegga