I'm using vscode to write some typescript, and I have set a breakpoint. When I open the Debug pane and ask it to evaluate an object, what is it doing to produce the string representation?
The reason I am asking is because I am using this solution to control the way that console.log
renders an instance of a class, and it works great -- but it doesn't seem to impact the way the object is rendered in the debugger.
To be more specific, the below code (also available in the typescript sandbox here) results in the desired output from console.log. However, when I set a breakpoint just before the console.log
line and evaluate myObj
in the debugger, what's displayed is
cls {property: 'property', hello: 'override', newProperty: 'new property'}
rather than
Greeter3Generated {property: 'property', hello: 'override', newProperty: 'new property'}
Code in question:
function classDecorator3<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const cls = class extends constructor {
newProperty = "new property";
hello = "override";
};
Object.defineProperty(cls, 'name', {
get: () => `${constructor.name}Generated`
});
return cls
}
@classDecorator3
class Greeter3 {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
const myObj = new Greeter3("world")
console.log(myObj);
//=> Greeter3Generated: { "property": "property", "hello": "override", "newProperty": "new property" }
You need to define Symbol.toStringTag
. Also, you can remove the hack which overrides the native constructor.name
:
function classDecorator3<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
[Symbol.toStringTag] = `${constructor.name}Generated`;
};
}
@classDecorator3
class Greeter3 {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
const myObj = new Greeter3("world");
console.log(myObj);
//=> Greeter3Generated: { "property": "property", "hello": "override", "newProperty": "new property" }
Demo with plain JavaScript (to execute with developer tools opened):
function classDecorator3(
constructor
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
[Symbol.toStringTag] = `${constructor.name}Generated`;
};
}
const GeneratedClass = classDecorator3(class Greeter3 {
property = "property";
hello;
constructor(m) {
this.hello = m;
}
});
const myObj = new GeneratedClass("world");
console.log(myObj);
debugger;
Result in Node.js:
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