Start learning free

LESSON 611 OF 639 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in TypeScript in TypeScript

Lesson

TL ; DR:

Give a class a toString method that returns a string. TypeScript calls it whenever the object becomes text, as in String(tom).


class Cat {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    toString(): string {
        return "Cat named " + this.name;
    }
}

console.log(String(new Cat("Tom")));   // Cat named Tom


Full lesson:

Every object already has a toString method. The default one isn't much use. It gives the same text for every object:

[object Object]

Write a toString method in your class, and it replaces the default. It returns the text that stands for the object.

JavaScript calls it whenever the object becomes a string. String(tom) does that. So do `I have ${tom}` and "I have " + tom.

There is one catch. console.log(tom) alone doesn't call toString. It shows the object's fields instead, like Cat { name: 'Tom' }. Turn the object into a string first.

toString takes no parameters. It must return the text, not print it.


Your task

The Dog class below has a name and an age. Add a toString method to it.

It returns the name, then " is ", the age and " years old". The code at the bottom prints String(rex) and String(bella).

Expected output:

Rex is 3 years old
Bella is 5 years old
STEP 1 OF 2
    Ctrl + Enter to check

    Printing Objects in TypeScript

    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free