我正在处理一个包含 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.ts是 reused在 client避免重复代码。
我是作者。
关于typescript - 在客户端和服务器之间共享类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65045106/