Let's say I have a class Person
which looks like this:
class Person { constructor( public firstName: string, public lastName: string, public age: number ) {} }
I have overridden the toString
method as follows.
public toString(): string { return this.firstName + ' ' + this.lastName; }
Now I expect to be able to do the following, which works in runtime:
function alertMessage(message: string) { alert(message); } alertMessage(new Person('John', 'Smith', 20));
But this still gives me this error:
TS2345: Argument of type 'Person' is not assignable to parameter of type 'string'.
How can I assign a Person
to this string
argument?
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Your Node class does not override the toString() method and falls back to use the Object. toString() method instead. Also I think it is a bit confusing that you add a value but return a Node instead of a value with get(). Update: to print the value of your Node add the following code to your Node class.
Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.
Overriding toString
works kind of as expected:
class Foo { private id: number = 23423; public toString = () : string => { return `Foo (id: ${this.id})`; } } class Bar extends Foo { private name:string = "Some name"; public toString = () : string => { return `Bar (${this.name})`; } } let a: Foo = new Foo(); // Calling log like this will not automatically invoke toString console.log(a); // outputs: Foo { id: 23423, toString: [Function] } // To string will be called when concatenating strings console.log("" + a); // outputs: Foo (id: 23423) console.log(`${a}`); // outputs: Foo (id: 23423) // and for overridden toString in subclass.. let b: Bar = new Bar(); console.log(b); // outputs: Bar { id: 23423, toString: [Function], name: 'Some name' } console.log("" + b); // outputs: Bar (Some name) console.log(`${b}`); // outputs: Bar (Some name) // This also works as expected; toString is run on Bar instance. let c: Foo = new Bar(); console.log(c); // outputs: Bar { id: 23423, toString: [Function], name: 'Some name' } console.log("" + c); // outputs: Bar (Some name) console.log(`${c}`); // outputs: Bar (Some name)
What can sometimes be an issue though is that it is not possible to access the toString
of a parent class:
console.log("" + (new Bar() as Foo));
Will run the toString on Bar, not on Foo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With