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.