首页 > 解决方案 > 打字稿扩展类型与接口

问题描述

这可能是一个相对菜鸟的问题,我有一个界面

interface Employee {
   name: string
}

我想在它被保存到数据库后有一个扩展版本:

interface EmployeeDb {
   id: string,
   name: string
}

我想在处理检查时区分它,以便在我的存储中保存数据后,类型检查器不会抱怨没有 id 值。意思是我想避免使用这个:

interface Employee {
   id?: string,
   name: string
}

所以我不必到处检查 id 。

所以我试图这样做:

type Employee = {
   name: string
}

type IDatabaseObject<T> = {
  id: IDatabaseObjectId;
  [P in keyof T]: T[P];
};

type EmployeeDb = IDatabaseObject<Employee>

IDE 使用顶级语法给出错误

计算属性名称必须是“字符串”、“数字”、“符号”或“任意”类型。ts(2464)

所以我尝试使用接口并扩展它

interface IDatabaseObject { 
   id: string
}

interface EmployeeDb extends Employee, IDatabaseObject {}

但是在后端代码中,当我尝试使用此设置时,我再次收到来自 vscode eslint 的错误。我这里有一个小代码,可以将数据添加到本地存储,生成一个 id 并返回数据。见代码:

class DbAsyncStorageTemplate<
    InputDataType,
    OutputDataType extends IDatabaseObject
> {

    async addEntry(object: InputDataType): Promise<OutputDataType> {

        const id: string = generateUuid()
        const dbObject = { id, ...object }
        dbObject.id = id

        // add the item to AsyncStorage directly
        await AsyncStorage.setItem(id, JSON.stringify(object))

        // ERROR HERE: return the new object
        return dbObject as OutputDataType
    } 
    }
}

但我从 IDE (eslint) 收到最后一行的错误

'{ id: string; 类型的转换 } & InputDataType' 键入 'OutputDataType' 可能是一个错误,因为这两种类型都没有与另一种充分重叠。如果这是故意的,请先将表达式转换为“未知”。'{ 标识:字符串;} & InputDataType' 可分配给'OutputDataType' 类型的约束,但'OutputDataType' 可以用约束'any' 的不同子类型来实例化。

关于如何正确执行此操作的任何建议?

标签: javascripttypescript

解决方案


我相信您正在寻找类型的交集

type Employee = {
   name: string
}

type EmployeeDb = {
  id: string;
} & Employee;

您还可以根据需要定义原始数据库接口和使用PickOmit实用程序。

选择实用程序

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

推荐阅读