Cannot invoke an object which is possibly ‘undefined’.ts(2722)


<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<div id="content"></div>  

<script>
function someFunction(obj) {
  // Check if the object is defined before invoking it
  if (typeof obj !== 'undefined') {
    obj.method(); // Invoking the method of the object
  }
}

// Example usage
var myObject = {
  method: function() {
    console.log("Method invoked");
  }
};

someFunction(myObject); // Method invoked

var anotherObject;

someFunction(anotherObject); // Nothing happens, as the object is undefined
</script>
</html>

Related Post

Leave a comment