TypeScript override ToString()

Duncan Luk picture Duncan Luk · Feb 12, 2016 · Viewed 54.7k times · Source

Let's say I have a class Person which looks like this:

class Person {
    constructor(
        public firstName: string,
        public lastName: string,
        public age: number
    ) {}
}

Is it possible to override the toString() method in this class, so I could do something like the following?

function alertMessage(message: string) {
    alert(message);
}

alertMessage(new Person('John', 'Smith', 20));

This override could look something like this:

public toString(): string {
    return this.firstName + ' ' + this.lastName;
}

Edit: This actually works. See answers below for details.

Answer

Nypan picture Nypan · Feb 12, 2016

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.