Custom toString() method not executed when object is created using object literal syntax

Currently, I am facing an issue with my code. I have a class called Foo which has overridden the default implementation of toString().

class Foo {
   bar: string;

   toString(): string {
      return this.bar;
   }
}

Whenever I create a new variable using a typed object literal and then call toString() on that object, it seems to invoke the standard JavaScript implementation instead of Foo.toString(), resulting in "[object Object]" being printed in the console.

let foo : Foo  = {
   bar: "baz"
}


console.log(foo.toString()) // does not invoke Foo.toString()

Interestingly, when I use the new operator to create the object, everything works perfectly:

let foo: Foo = new Foo();
foo.bar = "baz"
console.log(foo.toString()); // prints out "baz"

I am trying to figure out what could be going wrong in the first scenario. The second alternative works fine but given the complexity of the Foo object's attributes, it leads to verbose object initializations which I'd like to avoid.

Answer №1

Let's compare two examples:

let myObject : Object  = {
   key: "value"
}

In this first case, you're defining an object literal and assigning it the type Object. Although it's not a true instance of Object, it will use the default implementation of toString().

Now, in the second example:

let myObject: Object = new Object();

Here, you're actually creating a real instance of Object with your custom override of toString() in place.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

Lazy Loading fails to deliver for Ajax Requests

I recently integrated lazy loading following David Walsh's advice (tip 1) and it initially worked perfectly. However, I encountered an issue when the images were filtered and reloaded with an ajax request. The website is built on Rails, and the images ...

What could be causing the javascript slidetoggle function to keep closing?

I have a link on a page that toggles the search form on and off. Let's say you search for Spring term classes, then you want to search for a new term and click "Start a new Search." The link works great and toggles just fine...BUT the toggle automatic ...

React.map does not retrieve the specific value

I am facing an issue with my list of items. I have implemented it using mui list, and I have also added a button for editing the list. However, when I click on an item, I am getting the value of the last item instead of the one I clicked on. Below is my f ...

What is the process for reaching individuals within a nested object?

I have been struggling to access the elements of a nested object without any success. Despite looking through similar questions on stackexchange (such as this), I have not been able to resolve my issue. I attempted to access the final element using console ...

Switch up the color of the following-mouse-div in real-time to perfectly complement the color that lies underneath it

I am trying to create a div that changes color based on the complementary color of whatever is underneath the mouse pointer. I want it to follow the mouse and dynamically adjust its color. This functionality is similar to what Gpick does: https://www.you ...

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

Provide Chai/Mocha with a selection of essential keys that need to be incorporated

It appears that running the following code: describe( 'Add Youtube', function () { it( 'should return the video data, including user, title and content fields', function ( done ) { this.timeout( 5000 ) request({ ...

Turn off Appbar padding at the top and bottom

I am looking to create a customized box within the Appbar that spans the full height, as illustrated in the image below: https://i.stack.imgur.com/CFMo0.jpg However, the default Appbar provides padding from all sides to its internal elements, leading to ...

What is the process for cancelling a pending request using jQuery in JavaScript Selenium?

My website has a high volume of users clicking on one button. Waiting for long-pending ajax requests to get responses, sometimes over a minute, seems nonsensical. I understand how to wait for the response, but how can I cancel it? How do I cancel all pend ...

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

Learning how to retrieve the ID and Title using Jquery

Hello, I'm having an issue with my UL and LI elements. They work fine with the click function, but I can't seem to get the title when trying to access it. Example: // Works fine, but can't access the title $("#list li").on('click&ap ...

"Generate a series of dropdown menus with choices using either jQuery or AngularJS from a JSON dataset

I'm in need of assistance. I want to generate select dropdowns dynamically based on data retrieved from my REST API, which is in JSON format. How can I dynamically inject these selects into my HTML? Below is an example data structure: JSON data fetch ...

Data-bind knockout select knockout bind data

Hello! I am a beginner at using knockout and I have encountered an issue with data-binds and the "option" binding. My goal is to display two drop downs populated with data from my database. Surprisingly, I have managed to get the first drop down working pe ...

When running `npm start`, if you encounter an error message that says `npm ERR`,

When attempting to run this JS project on my Mac using this JS project, I encountered an npm error after typing npm start: https://i.sstatic.net/o2UZj.png Despite searching various websites for a solution, I have already included these lines in my packag ...

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

Get the application/pdf document that was just sent to you from the software backend

I am facing an issue with downloading a PDF file sent from the backend. Upon receiving a blob response, I notice that when I download and view the file, the sheets are empty, matching the expected number of sheets. Could this be a coding problem? Current ...

Creating a constant in an AngularJS module: The definitive guide to defining module-specific constants

Within a page, numerous Angular modules are present. I have set up a constant for each module containing the version number. var module1 = angular.module('module1').constant('version', '1.2.3'); var module2 = angular.module(& ...

Interactive marker popup appearing beyond the boundaries of the map container

Our popups are set to display outside of the map container initially, but when the map is moved, they adjust to fit inside the container with the correct anchor. However, upon inspecting the DOM, we noticed that the popups do not always have the correct an ...