Answer a question

As a follow-up question to this: TypeScript override ToString()

Let's say we have a Person class and we're overriding toString like this:

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

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

So, as mentioned in the original question, this works fine when doing console.log("" + myPerson);, however when examining an instance of Person in a debugger the toString seems to be ignored and the default display is shown. I tested this both against Google Chrome's debugger (hovering over a variable) and against VS Code's debugger (both hovering over a variable, and looking in the "locals" tab).

Is there any way to make one or both debuggers respect the toString override?

Note: It doesn't matter if I use the lambda version of toString, the results are the same.

Answers

This might help: v1.69 release notes: toString() variable previews.

If a variable or property has a custom toString() method, it will be called to render the preview in the VARIABLES view and hovers. This is an improvement over generic object previews for complex types that have good string representations.

For example, VS Code's Range has a toString method that makes it easier to digest at a glance:

demo of debug variables view showing the toString() call

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐