You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中为同一数据集创建多类型是否合理?含读写库示例

在TypeScript中为同一数据集定义多个类型的正确性确认

完全可以这么做,而且这是TypeScript里非常常见的最佳实践。

你的示例思路是对的,只是语法上要注意Type需小写为type,正确的定义如下:

type WritePost = { title: string, description: string }
type ReadPost = { id: number, createdAt: Date, title: string, description: string }

这种拆分方式的优势很明确:

  • 写入数据库时,只传递业务侧需要提交的字段(title和description),避免传入id、createdAt这类由数据库自动生成的冗余字段
  • 读取数据时,能获取包含完整元信息的结构,满足业务层对数据详情的需求

另外,为了避免重复定义相同字段,还可以通过类型扩展优化代码:

type WritePost = { title: string, description: string }
type ReadPost = WritePost & { id: number, createdAt: Date }

这种写法既保证了字段的一致性,又减少了代码冗余。

内容的提问来源于stack exchange,提问作者Leonardo Rocchini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:02:35