首页 > 解决方案 > 在为数据库行定义打字稿接口时,我应该扩展还是使用可选道具?

问题描述

我有一个带有数据库表“部门”的应用程序

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
}

标签: typescript

解决方案


推荐阅读