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

avatar

Last updated: Feb 28, 2024 Reading time · 4 min

banner

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

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.

left hand side of assignment expression may not be optional property

We aren't allowed to use the optional chaining (?.) operator on the left-hand side of an assignment.

# Use an if statement as a type guard to solve the error

To solve the error, use an if statement as a type guard before the assignment.

use if statement as type guard to solve the error

We used the loose not equals operator (!=), to check if the variable is NOT equal to null and undefined .

This works because when compared loosely, null is equal to undefined .

The if block is only run if employee doesn't store an undefined or a null value.

This is similar to what the optional chaining (?.) operator does.

# Using the non-null assertion operator to solve the error

You might also see examples online that use the non-null assertion operator to solve the error.

The exclamation mark is the non-null assertion operator in TypeScript.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined .

Here is an example of using this approach to set a property on an object.

using non null assertion to solve the error

In most cases, you should use a simple if statement that serves as a type guard as we did in the previous code sample.

# Avoiding the error with a type assertion

You can also use a type assertion to avoid getting the error. However, this isn't recommended.

avoiding the error with type assertion

The (employee as Employee) syntax is called a type assertion.

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the employee variable will have a type of Employee and not to worry about it.

This could go wrong if the variable is null or undefined as accessing a property on a null or an undefined value would cause a runtime error.

# Using the logical AND (&&) operator to get around the error

You can also use the logical AND (&&) operator to avoid getting the error.

using logical and operator to get around the error

The logical AND (&&) operator checks if the value to the left is truthy before evaluating the statement in the parentheses.

If the employee variable stores a falsy value (e.g. null or undefined ), the code to the right of the logical AND (&&) operator won't run at all.

The falsy values in JavaScript are: false , undefined , null , 0 , "" (empty string), NaN (not a number).

All other values are truthy.

However, this approach can only be used to assign a single property at a time if the value is not equal to null and undefined .

# The optional chaining operator should only be used when accessing properties

The optional chaining (?.) operator short-circuits if the reference is equal to null or undefined .

The optional chaining (?.) operator will simply return undefined in the example because employee has a value of undefined .

The purpose of the optional chaining (?.) operator is accessing deeply nested properties without erroring out if a value in the chain is equal to null or undefined .

However, the optional chaining operator cannot be used on the left-hand side of an assignment expression.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Check the Type of a Variable in TypeScript
  • Exclamation Mark (non-null assertion) operator in TypeScript
  • The ?. operator (optional chaining) in TypeScript
  • Declare and Type a nested Object in TypeScript
  • How to Add a property to an Object in TypeScript
  • Check if a Property exists in an Object in TypeScript
  • The left-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Airbrake logo144-1

  • Get Started

Jan 26, 2017 6:00:03 AM | JavaScript - ReferenceError: invalid assignment left-hand side

Today we examine the invalid assignment error, which is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.

Next on the list in our extensive JavaScript Error Handling series we're going to examine the Invalid Left-Hand Assignment error in greater detail. The Invalid Left-Hand Assignment error is a sub-object of ReferenceError and is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.

In this post we'll look at a few code examples to illustrate some common methods of producing an Invalid Left-Hand Assignment error, as well as examine how to handle this error when it rears its ugly head. Let the party begin!

The Technical Rundown

  • All JavaScript error objects are descendants of the  Error  object, or an inherited object therein.
  • The  ReferenceError  object is inherited from the  Error  object.
  • The Invalid Left-Hand Assignment error is a specific type of ReferenceError object.

When Should You Use It?

As one of the simplest JavaScript errors to understand, the Invalid Left-Hand Assignment error appears in only a handful of situations in which code is attempting to pass an assignment incorrectly. While this is generally thought of as a syntactic issue, JavaScript defines this particular assignment error as a ReferenceError, since the engine effectively assumes an assignment to a non-referenced variable is being attempted.

The most common example of an Invalid Left-Hand Assignment error is when attempting to compare a value using a assignment operator (=), rather than using a proper comparison operator (== or ===). For example, here we're attempting to perform a basic comparison of the variable name with the values John or Fred. Unfortunately, we've made the mistake of using the assignment operator =, instead of a comparison operator such as == or ===:

try { var name = 'Bob'; if (name = 'John' || name = 'Fred') { console.log(`${name} returns!`) } else { console.log(`Just ${name} this time.`) } } catch (e) { if (e instanceof ReferenceError) { printError(e, true); } else { printError(e, false); } }

Sure enough, rather than giving us an output, the JavaScript engine produces the expected Invalid Left-Hand Assignment error:

It's worth noting that catching an Invalid Left-Hand Assignment error with a typical try-catch block is particular difficult, because the engine parses the code from inside out, meaning inner code blocks are parsed and executed before outer blocks. Since the issue of using a = assignment operator instead of a == comparison operator means the actual structure of the code is changed from the expected, the outer try-catch fails to be parsed and properly executed. In short, this means Invalid Left-Hand Assignment errors are always "raw", without any simple means of catching them.

Another common method for producing an Invalid Left-Hand Assignment error is when attempting to concatenate a string value onto a variable using the addition assignment += operator, instead of the concatenation operator +. For example, below we're attempting to perform concatenation on the name variable on multiple lines, but we've accidentally used the += operator:

try { var name = 'Bob' += ' Smith';

console.log(`Name is ${name}.`); } catch (e) { if (e instanceof ReferenceError) { printError(e, true); } else { printError(e, false); } }

This isn't the syntax JavaScript expects when concatenating multiple values onto a string, so an Invalid Left-Hand Assignment error is thrown:

To resolve this, we simply need to replace += with the concatenation operator +:

try { var name = 'Bob' + ' Smith';

Now we skip the Invalid Left-Hand Assignment error entirely and get our expected output indicating the full name stored in the name variable:

To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.

Written By: Frances Banks

You may also like.

 alt=

Dec 28, 2016 8:00:56 AM | JavaScript Error Handling - ReferenceError: assignment to undeclared variable “x”

Feb 15, 2017 7:41:35 am | javascript error handling: syntaxerror: "use strict" not allowed in function with non-simple parameters, may 21, 2017 9:00:51 am | javascript errors - syntaxerror: test for equality mistyped as assignment.

© Airbrake. All rights reserved. Terms of Service | Privacy Policy | DPA

  • Skip to main content
  • Select language
  • Skip to search
  • ReferenceError: invalid assignment left-hand side

ReferenceError .

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and a comparison operator , for example. While a single " = " sign assigns a value to a variable, the " == " or " === " operators compare a value.

In the if statement, you want to use a comparison operator ("=="), and for the string concatenation, the plus ("+") operator is needed.

  • Assignment operators
  • Comparison operators

Document Tags and Contributors

  • ReferenceError
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • JavaScript basics
  • JavaScript technologies overview
  • Introduction to Object Oriented JavaScript
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is not a legal ECMA-262 octal constant
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ; before statement
  • SyntaxError: missing ] after element list
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: variable "x" redeclares argument
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: unreachable code after return statement
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 5 support in Mozilla
  • ECMAScript 6 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project
  • Skip to main content

UDN Web Docs: MDN Backup

  • ReferenceError: invalid assignment left-hand side

The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single " = " sign was used instead of " == " or " === ".

ReferenceError .

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and a comparison operator , for example. While a single " = " sign assigns a value to a variable, the " == " or " === " operators compare a value.

Typical invalid assignments

In the if statement, you want to use a comparison operator ("=="), and for the string concatenation, the plus ("+") operator is needed.

  • Assignment operators
  • Comparison operators
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • AggregateError
  • ArrayBuffer
  • AsyncFunction
  • BigInt64Array
  • BigUint64Array
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Bitwise operators
  • Comma operator
  • Conditional (ternary) operator
  • Destructuring assignment
  • Function expression
  • Grouping operator
  • Logical operators
  • Nullish coalescing operator
  • Object initializer
  • Operator precedence
  • Optional chaining
  • Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function* expression
  • in operator
  • new operator
  • void operator
  • async function
  • for await...of
  • function declaration
  • import.meta
  • try...catch
  • Arrow function expressions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • Class fields
  • constructor
  • Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration "x" before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the "delete" operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: "x" is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: X.prototype.y called on incompatible type
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use "in" operator to search for "x" in "y"
  • TypeError: cyclic object value
  • TypeError: invalid "instanceof" operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript ReferenceError – Invalid assignment left-hand side

This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment.

Error Type:

Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.

Basic Example of ReferenceError – Invalid assignment left-hand side, run the code and check the console

Example 1: In this example, “=” operator is misused as “==”, So the error occurred.

Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.

Output: 

Please Login to comment...

Similar reads.

  • Web Technologies
  • JavaScript-Errors

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

ReferenceError: invalid assignment left-hand side

The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single " = " sign was used instead of " == " or " === ".

ReferenceError .

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and an equality operator , for example. While a single " = " sign assigns a value to a variable, the " == " or " === " operators compare a value.

Typical invalid assignments

In the if statement, you want to use an equality operator ("=="), and for the string concatenation, the plus ("+") operator is needed.

  • Assignment operators
  • Equality operators

© 2005–2021 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side

This forum is now read-only. Please use our new forums! Go to forums

invalid left hand side in assignment expression useref

Syntax Error: "Invalid Left-hand Side in assignment."

I am unsure what else is necessary in my code. My syntax is as follows:

var isEven = function(number) {

if (number % 2 === 0){ return true; }

else if (isNan(number) = true) { return “This is not a number!”; }

else { return false; }

isEven (“r”)

First, I would like to know what this error code means. Secondly, I would like further insight into how one would use isNaN in this code.

Answer 5605035486f55253a300022e

if you want to compare two values you need to use == or ===, = just tries to assign the value on the left to the variable on the right. And here is the problem as you have a value on the left and not a variable which is why you get that:

To get rid of it just fix the comparison:

or get rid of the == true or === true and just use:

as a comparision with true is always what it was before e.g.

if isNan(number) is false:

and if it is true:

invalid left hand side in assignment expression useref

Answer 560a184286f552cb7c000371

if(number%2===0) { return true; } else if (isNaN(number)===true) { return “Your input type is notcorrect”; }

else { return false; } };isEven(“hi”);

invalid left hand side in assignment expression useref

worked for me

Popular free courses

Learn javascript.

Invalid left-hand side in assignment expression

Hello. I am attempting to create a self-generating biology question that randomly generates three numbers for the problem question, then asks a yes or no question. When I was attempting to create the function that checks for the answer to the question and compared it to the student input, I get the “Invalid left-hand side in assignment expression”

My code is here, line 33 in the JavaScript window: https://codepen.io/KDalang/pen/OJpEdQB

Here is the specific line in question: if (chiTotal <= 3.841 && input=“Yes”) What did I do wrong?

= is assignment of a value to a variable == is weak comparison (with type coercion) === is strong comparison (probably what you want)

Hey thanks for the quick reply! I actually want it to be a “less than or equal to” and I used <=. <== and <=== don’t do anything either.

Edit: Nevermind, I understand now.

Do you try to compare values or do you try to assign a value?

Oh my gosh! Sorry its 2a.m. over here I understand what you and JeremyLT are saying now. Thanks so much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Angular error- "The left-hand side of an assignment expression may not be an optional property access.ts"?

In my Angular typescript file I have following code. I need help to solve this typescript error

I am getting the following error

I have created custom pipe where if I get loop through text and search for a word, if word is present in given text I add highlighted class to it so that, I can hilight that word with pink color

  • runtime-error

Paritosh M's user avatar

3 Answers 3

Just remove the question mark in

for the error.

It should be

Because that ? making document.querySelector('.highlighted') as optional and in the right we are assigning value to that.

But it will set the pink color in the first item that has the class 'highlighted'. So you need to loop through the elements or add a pink-color class to it. And set the background color of that class item to pink

Try the below code for changing all elements with the class highlighted.

Ckeck this https://stackblitz.com/edit/angular-services-example-ygmmaq?file=src/app/app.component.html

Jobelle's user avatar

  • 3 On removing ? from document.querySelector<HTMLElement>('.highlighted').style.backgroundColor = 'white' ` it says Object is possibly 'null'.ts(2531) –  Paritosh M Commented Feb 3, 2021 at 18:40
  • Try the last piece of code. That will work. It has the check, like whether it exists or not. –  Jobelle Commented Feb 5, 2021 at 4:06
  • I tried above code at forEach((item:HTMLElement) it says Argument of type '(item: HTMLElement) => void' is not assignable to parameter of type '(value: Element, key: number, parent: NodeListOf<Element>) => void'. Types of parameters 'item' and 'value' are incompatible. Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 107 more. –  Paritosh M Commented Feb 6, 2021 at 0:50
  • @ParitoshM I have updated the answer with stackblits link. Please check that :) –  Jobelle Commented Feb 10, 2021 at 3:42
  • @ParitoshM store the result of the querySelector in a variable first. –  Henridv Commented Nov 15, 2021 at 21:05

This may help others for late reply.

vidya's user avatar

The casting was not set right on the document object

Refer to this link for more info Typescript 3.7@beta Optional Chaining operator using problem

Richie50's user avatar

  • I am confused can you take whole ngAfterViewInit() code and then add your code? –  Paritosh M Commented Feb 3, 2021 at 3:45
  • @ParitoshM removing the lifecycle hook doesn't change the static type checking error. –  Richie50 Commented Feb 3, 2021 at 3:51
  • Okay but what should I do in place where I have just this single line defined in other function? document.querySelector<HTMLElement>('.highlighted')?.style.backgroundColor = 'white'; –  Paritosh M Commented Feb 3, 2021 at 3:57
  • I changed the answer. You have to assign the querySelector to a variable. –  Richie50 Commented Feb 3, 2021 at 3:59
  • If I write as above <HTMLElement>document.querySelector('.highlighted')?.style.backgroundColor = 'white'; ` it says Property 'style' does not exist on type 'Element'.ts(2339) –  Paritosh M Commented Feb 3, 2021 at 4:00

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged angular typescript runtime-error or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Why is Excel not counting time with COUNTIF?
  • Why do individuals with revoked master’s/PhD degrees due to plagiarism or misconduct not return to retake them?
  • I need to better understand this clause in an independent contract agreement for Waiverability:
  • Why are these simple equations so slow to `Solve`?
  • Is an invalid date considered the same as a NULL value?
  • Suitable tool bag for vintage centre pull rim brake bike
  • Why would luck magic become obsolete in the modern era?
  • Could a 3D sphere of fifths reveal more insights than the 2D circle of fifths?
  • To what extent do value sets determine polynomials mod p?
  • how to include brackets in pointform latex
  • Why does Air Force Two lack a tail number?
  • How to interpret coefficients of logistic regression using natural cubic splines?
  • Looking for a British childrens book, I think from the 1950s, called "C-for-Charlie"
  • Justification for the Moral Ought
  • What's the polarity of this electrolytic capacitor symbol?
  • How are USB-C cables so thin?
  • Secret super people
  • Isn't an appeal to emotions in fact necessary to validate our ethical decisions?
  • Package 'gettext' has no installation candidate, but package exists
  • Short story about a committee planning to eliminate 1 in 10 people
  • Is groff ignoring `.nh` command?
  • Did Newton predict the deflection of light by gravity?
  • Why did Borland ignore the Macintosh market?
  • How much air escapes into space every day, and how long before it makes Earth air pressure too low for humans to breathe?

invalid left hand side in assignment expression useref

IMAGES

  1. javascript

    invalid left hand side in assignment expression useref

  2. Invalid Left Hand Side In Assignment

    invalid left hand side in assignment expression useref

  3. Invalid Left Hand Side In Assignment

    invalid left hand side in assignment expression useref

  4. R Error : invalid (do_set) left-hand side to assignment (2 Examples)

    invalid left hand side in assignment expression useref

  5. Invalid left-hand side in assignment in JavaScript [Solved]

    invalid left hand side in assignment expression useref

  6. React成长路之踩坑路 Module build failed: SyntaxError: Invalid left-hand side

    invalid left hand side in assignment expression useref

VIDEO

  1. 10

  2. Learn useRef React Hook in 10 Minutes

  3. Learn useEffect In 13 Minutes

  4. React Hooks

  5. React Hooks useRef Tutorial

  6. Strong typing useRef : React + TypeScript

COMMENTS

  1. SyntaxError: invalid assignment left-hand side

    Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference, so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed. js. function foo() { return { a: 1 }; } foo ...

  2. ReferenceError: Invalid left-hand side in assignment

    Common reasons for the error: use of assignment ( =) instead of equality ( == / ===) assigning to result of function foo() = 42 instead of passing arguments ( foo(42)) simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42.

  3. Invalid left-hand side in assignment expression

    2. The problem is with using string.charAt () on the left hand side. That is not possible as you're trying to assign something to the result of a function, all in the same call. Store the value of string.charAt () in an intermediary variable and it should work.

  4. Why I get "Invalid left-hand side in assignment"?

    7. The problem is that the assignment operator, =, is a low-precedence operator, so it's being interpreted in a way you don't expect. If you put that last expression in parentheses, it works: for(let id in list)(. (!q.id || (id == q.id)) &&. (!q.name || (list[id].name.search(q.name) > -1)) &&. (result[id] = list[id]) ); The real problem is ...

  5. Invalid left-hand side in assignment in JavaScript [Solved]

    The engine interprets the single equal sign as an assignment and not as a comparison operator. We use a single equals sign when assigning a value to a variable.

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

    The optional chaining (?.) operator will simply return undefined in the example because employee has a value of undefined.. The purpose of the optional chaining (?.) operator is accessing deeply nested properties without erroring out if a value in the chain is equal to null or undefined. However, the optional chaining operator cannot be used on the left-hand side of an assignment expression.

  7. JavaScript

    Today we examine the invalid assignment error, which is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.

  8. ReferenceError: invalid assignment left-hand side

    There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and a comparison operator, for example. While a single " = " sign assigns a value to a variable, the " == " or " === " operators compare a value.

  9. How to fix SyntaxError

    When you attempt to assign a value to a literal like a number, string or boolean it will result in SyntaxError: Invalid Assignment Left-Hand Side. Example: 5 = x; Output. SyntaxError: invalid assignment left-hand side Resolution of error

  10. ReferenceError: invalid assignment left-hand side

    The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single "=" sign was used instead of "==" or "===". ... SyntaxError: invalid regular expression flag "x" SyntaxError: missing ) after argument list; SyntaxError: missing ) after condition;

  11. Invalid assignment left-hand side

    This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single "=" sign instead of "==" or "===" is an Invalid assignment. Message:

  12. ReferenceError: invalid assignment left-hand side

    ReferenceError: invalid assignment left-hand side The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single "=" sign was used instead of "==" or "===". ... Errors: Deprecated expression closures. Errors: Deprecated octal. Errors: Deprecated source map pragma ...

  13. Syntax Error: "Invalid Left-hand Side in assignment."

    And here is the problem as you have a value on the left and not a variable which is why you get that: Syntax Error: "Invalid Left-hand Side in assignment." To get rid of it just fix the comparison: isNan(number) == true. or. isNan(number) === true. or get rid of the == true or === true and just use: isNan(number)

  14. Invalid left-hand side in assignment expression

    Hello. I am attempting to create a self-generating biology question that randomly generates three numbers for the problem question, then asks a yes or no question. When I was attempting to create the function that checks for the answer to the question and compared it to the student input, I get the "Invalid left-hand side in assignment expression" My code is here, line 33 in the JavaScript ...

  15. Uncaught ReferenceError: Invalid left-hand side in assignment

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  16. javascript

    0. You're first approach is about retrieval data. Whereas the second part is about assigning the data. Here You're are assigning value to something function variable. May you need to change like below. function something(id, val){. document.getElementById(id).value = val; return document.getElementById(id).value; }

  17. javascript

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  18. Syntax Error: Invalid left-hand side in assignment expression

    3. I have received data from backend which contains a student object. The student contains a field named grade. I would like to explicitly update that value of the student object in my code: const {grade} = calculateNewGrade(student); // Syntax Error: Invalid left-hand side in assignment expression.

  19. Angular error- "The left-hand side of an assignment expression may not

    The left-hand side of an assignment expression may not be an optional property access.ts(2779) I have created custom pipe where if I get loop through text and search for a word, if word is present in given text I add highlighted class to it so that, I can hilight that word with pink color