Borislav Hadzhiev
Wed Mar 16 2022·2 min read
Photo by Brooke Cagle
The error "The left-hand side of an assignment expression may not be an
optional property access" occurs when we try to use optional chaining (?.) to
assign a property to an object. To solve the error, use an if
statement that
serves as a type guard instead.
Here is an example of how the error occurs.
type Employee = { name: string; country: string; }; let employee: Employee | undefined; // 👈️ could be undefined // ⛔️ Error: The left-hand side of an // assignment expression may not be // an optional property access.ts(2779) employee?.country = 'Germany';
We aren't allowed to use the optional chaining (?.) operator on the left-hand side of an assignment.
To solve the error, use an if
statement as a
type guard
before the assignment.
type Employee = { name: string; country: string; }; let employee: Employee | undefined; // 👈️ could be undefined if (employee != undefined) { employee.country = 'Germany'; }
We used the loose not equals operator (!=), which checks that the variable is
NOT equal to null
and undefined
.
The if
block is only ran if employee
does not store an undefined
or null
value, which is similar to what the
optional chaining (?.)
operator does.
You might also see examples online that use the non-null assertion operator to solve the error.
type Employee = { name: string; country: string; }; let employee: Employee | undefined; // 👈️ could be undefined employee!.country = 'Germany';
The exclamation mark is the non-null assertion operator. It removes null
and
undefined
from the type.
null
or undefined
.In most cases you should use a simple if
statement that serves as a type guard
like we did in the previous code snippet.
The optional chaining (?.) operator short-circuits if the reference is equal to
null
or undefined
.
type Employee = { name: string; country: string; }; let employee: Employee | undefined; // 👈️ could be undefined // 👇️ undefined console.log(employee?.country.toLowerCase());
The optional chaining operator will simply return undefined
in the example,
because employee
has a value of undefined
.
However, it can't be used in the left-hand side of an assignment expression.