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.

ts
obj.foo = "bar";

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

ts
obj?.foo = "bar";

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.

ts
obj?.foo = "bar";
Matt's signature

Share this article with your friends

`any` Considered Harmful, Except For These Cases

Discover when it's appropriate to use TypeScript's any type despite its risks. Learn about legitimate cases where any is necessary.

Matt Pocock
Matt Pocock

No, TypeScript Types Don't Exist At Runtime

Learn why TypeScript's types don't exist at runtime. Discover how TypeScript compiles down to JavaScript and how it differs from other strongly-typed languages.

Matt Pocock
Matt Pocock

Deriving vs Decoupling: When NOT To Be A TypeScript Wizard

In this book teaser, we discuss deriving vs decoupling your types: when building relationships between your types or segregating them makes sense.

Matt Pocock
Matt Pocock

NoInfer: TypeScript 5.4's New Utility Type

Learn how TypeScript's new utility type, NoInfer, can improve inference behavior by controlling where types are inferred in generic functions.

Matt Pocock
Matt Pocock