typescript - 将接口名称打印到控制台,如 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/
我认为没有,因为接口实际上并没有像类那样结束。只是看看是否有任何选择可以实现它
解决方案
您可以“品牌化”您的类型。
{ firstName: "something", lastName: "something" }
具有字面量类型{ firstName: string, lastName: string }
,但更一般地说只有 type { [key: string]: string }
。如果您关心,请修改 API 响应,或调整应用程序接收数据的方式以“标记”对象。
{ __type: "Person", firstName: "something", lastName: "something" }
这也称为“名义打字”
推荐阅读
- api - 如何使用 long curl 命令正确解析 YAML
- python-3.x - FastAPI 使用 POST 请求将文件下载到客户端
- javascript - Docker 后端部署找不到路径'/app/package.json' - DigitalOcean
- flutter - 我可以在原生启动画面上放置超过 2 个图像吗?
- sql - 在 oracle 中分隔数值和字符值
- python - Python世纪日期过程
- bootstrap-4 - 切换按钮问题
- xaml - 将自定义按钮插入 BottomBar 外壳
- arrays - C中数组的大小小于预期
- dependency-injection - 是否可以使用 Unity 作为与 Restier 结合使用的 DI 框架