typescript - 在为数据库行定义打字稿接口时,我应该扩展还是使用可选道具?
问题描述
我有一个带有数据库表“部门”的应用程序
ID | external_id | 姓名 |
---|---|---|
1 | 345 | 销售量 |
2 | 123 | 经济 |
它的类型定义可能如下所示:
interface Department {
id: number;
external_id: number;
name: string;
}
从数据库中获取部门的函数可能如下所示:
function getDepartement(id: number): Department {
db('department').getById(id)
}
现在,如果我添加了另一个用于添加部门的函数,该函数返回该部门新自动生成的 id,它可能如下所示:
function addDepartement(department: Department): number {
db('department').add(department)
}
为了不引发任何 Typescript 错误,我需要更新界面,以便“id”变为可选,因为当我添加部门时我没有这个。
interface Department {
id?: number;
external_id: number;
name: string;
}
它可以工作,但这也意味着每当我在代码中使用类型 Department 时,我都需要检查 id 是否实际定义,这在我看来只是噪音。
这是一个有点人为的例子,但希望你能明白我想要表达的意思。
您会改为使用两个接口,一个扩展另一个接口吗?
interface DepartmentBase {
name: string;
external_id: number
}
interface Department extends DepartmentBase {
id: number
}
解决方案
推荐阅读
- c# - 使用 C# 将给定 URL 的 XML 文件加载到 Visual Studio
- php - PHP 将一个 $ 数量的数组映射到一个变量数组,并将变量乘以它的正确数量
- excel - 使用 microsoft-graph excel API 刷新 excel powerquery
- c# - ASP.NET 唯一浏览器 ID
- temp-tables - 临时表存储在 GreenPlum 数据库中的什么位置?
- python - 在派对加载的数据上训练 Keras 模型
- c# - 我应该使用 System.Net.Http Nuget 包吗?
- jestjs - 测试失败并显示消息“OTransitionProperty”
- sql - 默认缺失数据
- javascript - 你如何处理小数(,)和javascript?