Issue
I'm trying to use the Typescript optional chaining operator but it threw 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:
const url = URI({
protocol: 'http',
hostname: 'example.org'
})
// This line threw
document.getElementById('output')?.innerHTML = url.toString()
How to resolve this problem?
Solution
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
Answered By - iamolegga
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.