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?
Optional chaining is not a feature specific to TypeScript.
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!
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.
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.
objectVariableName!.propertyName = 'some value to assign';
Please note the exclamation symbol i.e,!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With