typescript - 在客户端和服务器之间共享类型

标签 typescript server model client

我正在处理一个包含 Node.js、Express.js 和 TypeScript 后端(REST API)以及 React、Redux 和 TypeScript 前端的项目。
在后端,我创建了一些类型,例如:
型号/Product.ts

export type Product = {
    title: string
    description: string
    price: number
}
因此 REST API 正在发送如下响应:
{
  "data": [
     {"title": "Shoe", "Description": "This is a shoe.", "price": 20},
     {...}
   ] // inside here all the Products[]
}
在客户端上我想转换 data到类型 Product大批。但是由于前端和后端是不同的代码库并且是分开的,我仍然想利用前端使用类型的优势。但我想在不重复代码的情况下实现这一点。所以我不想在修改或添加模型时更新 2 个地方。
有人知道在客户端和服务器之间共享类型的最佳方式是什么吗?

I was thinking of something like creating an endpoint on the backend which the client can hit, then it writes all the models in a single file for example models.ts on the client. So I think I need to loop through every file inside /models/ on the backend then parsing it in a new file which is written on the client as models.ts. But is this really a good way? Does someone know a better way of achieving this structure?

最佳答案

您可以使用 TypeScript path mapping .
例子:
后端定义的类型 SampleTypes.tsreusedclient避免重复代码。
我是作者。

关于typescript - 在客户端和服务器之间共享类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65045106/

相关文章:

typescript - 点燃元素\lib\decorators.js : Unexpected token error

javascript - Angularfire2 错误 "Property ' downloadURL 在类型 'AngularFireUploadTask' 上不存在。”

java - 如何让Apache托管的公共(public)网页访问同一网络上的私有(private) Node 服务器?

python - 无法退出正在运行的 jupyter notebook 服务器

ruby-on-rails - 将 JSON 嵌套到事件记录中

python - 如何使用 Django 创建三联表

ASP.NET MVC 3 : best way manage a model with an image

json - 带有特殊字符的 typescript 字段

javascript - 使用 @ViewChild 按类名选择元素?

networking - 实现类似于 Spotify 的音频流服务