Typescript 3.7@beta Optional Chaining operator using problem

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.


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

Please note the exclamation symbol i.e,!