如何在前端和 Golang 后端之间共享类型定义?

huangapple go评论87阅读模式
英文:

How do I share type definitions between frontend and a Golang backend?

问题

我之前在前端(Angular)和后端(Express)都使用了TypeScript。为了共享类型定义,我这样做:

shared-type-file.ts

interface Kid{
  name: string;
  age: number;
}

然后在前端和后端都运行npm install。这样,我的数据结构在系统之间得到了良好的定义,并且对我帮助很大。

现在,如果我要将服务器切换到Go(可能是go-fiber),我该如何获得类似的功能?如何在系统之间保持数据结构的类型检查?

英文:

I was using typescript for both forntend(Angular) and backend(Express).

So to share type definition, I was doing:

shared-type-file.ts

interface Kid{
  name: string;
  age: number;
}

Then npm install it in both frontend and backend. Thus my data structure was well defined across systems and it helped me a lot.

Now if I'm switching my server to Go (maybe go-fibre) how do I obtain a similar functionality? How can I keep my data structures type-checked across the systems like that?

答案1

得分: 1

它们不是相同的语言,每种语言都有自己的类型系统。最常见的做法是手动创建类型,但一个好的主意是为后端API和它们使用的数据模式编写文档。

有一些工具可以帮助你将OpenAPI规范转换为TypeScript类型。这样,你只需要一次性记录类型,然后在TypeScript项目中自动生成它们。

例如:https://github.com/drwpow/openapi-typescript

英文:

They're not the same language and each of them has its own type system. The main go-to would be to create types manually but a good idea would be to have documentation for your backend APIs and the data schemas that they use.

There are tools that help you convert OpenAPI specs to typescript types. This way, you only need to document the types once and then just automatically generate them in your typescript project.

As an example: https://github.com/drwpow/openapi-typescript

huangapple
  • 本文由 发表于 2022年5月17日 16:05:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/72270282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定