Typescript 3.7@beta Optional Chaining operator using problem

Viewed 68495

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?

7 Answers
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

As mentioned here:

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.

If we go and see what properties the Element base class contains, you will see innerHTML.

This means that it is sure that an instance of Element(the result of getElementById) will have an innerHTML property, which is why you're getting the error.

This very short expression works for me nicely in typescript 4.0.3

let domEl: HTMLElement | null = document.querySelector("#app");
domEl && (domEl.style.color = "green");

in ES12 you can do this with Logical nullish assignment

document.getElementById('output')?.innerHTML ??= url.toString()

so the assignment will happen only if the left-hand expression is not nullish.

this is just like if you would do

if (document.getElementById('output')?.innerHTML) {
  document.getElementById('output').innerHTML = url.toString()
}

My exception was :

The left-hand side of an assignment expression may not be optional property access.

I received this error in typescript "~4.6.2" and solved it like.

let headingDom : HTMLElement | null = document?.querySelector('h1');
if(headingDom) headingDom.textContent = 'Hello World';
Related