带有打字稿的 vscode 调试器:是什么决定了对象的呈现方式?

bra*_*ahn 7 javascript typescript console.log visual-studio-code vscode-debugger

我正在使用 vscode 编写一些打字稿,并且设置了一个断点。当我打开 Debug 窗格并要求它评估一个对象时,它如何生成字符串表示?

我问的原因是因为我使用此解决方案来控制console.log呈现类实例的方式,并且效果很好——但它似乎不会影响调试器中呈现对象的方式。

更具体地说,下面的代码(也可在此处的打字稿沙箱中找到)从 console.log 产生所需的输出。但是,当我在该console.log行之前设置断点并myObj在调试器中进行评估时,显示的是

cls {property: 'property', hello: 'override', newProperty: 'new property'}
Run Code Online (Sandbox Code Playgroud)

而不是

Greeter3Generated {property: 'property', hello: 'override', newProperty: 'new property'}
Run Code Online (Sandbox Code Playgroud)

有问题的代码:

cls {property: 'property', hello: 'override', newProperty: 'new property'}
Run Code Online (Sandbox Code Playgroud)

Twi*_*her 2

你需要定义Symbol.toStringTag. 另外,您可以删除覆盖本机的 hack 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" } 
Run Code Online (Sandbox Code Playgroud)

使用纯 JavaScript 进行演示(在打开的开发人员工具下执行):

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" } 
Run Code Online (Sandbox Code Playgroud)

Node.js 中的结果:

Node.js 中的结果