首页 > 解决方案 > 将接口名称打印到控制台,如 chrome 开发工具中的类名

问题描述

我正在使用带有 TypeScript 的 Angular v8,目前我有一堆冗余类,让它们与我的后端模型的更改保持同步变得很痛苦。解决这个问题的方法是使用 Swagger,它就像一个魅力。

我的后端是 C#,我正在使用 swagger code-gen 来生成我的前端客户端及其模型。它非常光滑,我真的很喜欢它。

但是,我正在寻找一种方法来让模型名称打印到开发工具中的控制台,就像他们做类(使用类的名称)一样。但是,由于我大摇大摆似乎只生成接口而不是类,因此 chrome 只是将它作为 JSON 对象吐到控制台。

有没有办法让 chrome 开发工具在对象旁边打印接口名称?

class Person {
    public firstName: string;
  public lastName: string;
  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }
}

interface IPerson {
    firstName: string;
  lastName: string;
}

console.log(new Person('joe', 'dirt')); // friendly console message
console.log(<IPerson>{firstName: 'john', lastName: 'doe'}); // can't tell what type this is
console.log({firstName: 'john', lastName: 'doe'} as IPerson); // can't tell what type this is

https://jsfiddle.net/mswilson4040/yf8kowqn/

在此处输入图像描述

我认为没有,因为接口实际上并没有像类那样结束。只是看看是否有任何选择可以实现它

标签: typescriptgoogle-chrome-devtools

解决方案


您可以“品牌化”您的类型。

{ firstName: "something", lastName: "something" }具有字面量类型{ firstName: string, lastName: string },但更一般地说只有 type { [key: string]: string }。如果您关心,请修改 API 响应,或调整应用程序接收数据的方式以“标记”对象。

{ __type: "Person", firstName: "something", lastName: "something" }

这也称为“名义打字


推荐阅读