All Articles

Optional Chaining for Assignments Lands in Stage 1

Matt Pocock
Matt PocockMatt is a well-regarded TypeScript expert known for his ability to demystify complex TypeScript concepts.

In TypeScript, if you try to assign to a property of a possibly undefined object, you'll get an error:

'X' is possibly undefined.

obj.foo = "bar";
'obj' is possibly 'undefined'.18048
'obj' is possibly 'undefined'.

You might think that you can use the optional chaining syntax to fix this:

obj?.foo = "bar";
The left-hand side of an assignment expression may not be an optional property access.2779
The left-hand side of an assignment expression may not be an optional property access.

But you end up with an error:

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

This is because optional chaining is only for reading properties (or deleting properties), not for assigning to them.

But today, the optional chaining for assignments proposal has landed in Stage 1 of TC39.

If this proposal gets adopted into JavaScript, the code below will no longer error.

obj?.foo = "bar";
The left-hand side of an assignment expression may not be an optional property access.2779
The left-hand side of an assignment expression may not be an optional property access.
Matt's signature

Optional Chaining for Assignments Lands in Stage 1