Announcing: A Free Book, A New Course, A Huge Price Cut...
It's a massive ship day. We're launching a free TypeScript book, new course, giveaway, price cut, and sale.
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.2779The 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.2779The left-hand side of an assignment expression may not be an optional property access.
Share this article with your friends
It's a massive ship day. We're launching a free TypeScript book, new course, giveaway, price cut, and sale.
Learn why the order you specify object properties in TypeScript matters and how it can affect type inference in your functions.
Learn how to use corepack
to configure package managers in Node.js projects, ensuring you always use the correct one.
Learn how to strongly type process.env in TypeScript by either augmenting global type or validating it at runtime with t3-env.
Discover when it's appropriate to use TypeScript's any
type despite its risks. Learn about legitimate cases where any
is necessary.
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.