This Crazy Syntax Lets You Get An Array Element's Type
Learn how to extract the type of an array element in TypeScript using the powerful Array[number]
trick.
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
Learn how to extract the type of an array element in TypeScript using the powerful Array[number]
trick.
Learn how to publish a package to npm with a complete setup including, TypeScript, Prettier, Vitest, GitHub Actions, and versioning with Changesets.
Enums in TypeScript can be confusing, with differences between numeric and string enums causing unexpected behaviors.
Is TypeScript just a linter? No, but yes.
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.