javascript - 打字稿扩展类型与接口
问题描述
这可能是一个相对菜鸟的问题,我有一个界面
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' 的不同子类型来实例化。
关于如何正确执行此操作的任何建议?
解决方案
我相信您正在寻找类型的交集。
type Employee = {
name: string
}
type EmployeeDb = {
id: string;
} & Employee;
您还可以根据需要定义原始数据库接口和使用Pick
或Omit
实用程序。
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
推荐阅读
- c - 为什么对具有灵活数组成员的结构的初始化无效但对固定大小的数组成员有效?
- excel - 将 vbYesNo 输入框上的按钮更改为自定义选项
- python - 使用两个索引访问 pyomo 变量
- java - 为什么 C++ 使用指针指向链表中的下一个节点,而 C# 或 Java 等语言只使用类 Node 的名称?
- html - 如何在 chrome/Firefox 上自动播放音频
- android - kotlin 惰性初始化属性不能在 init 块中修改
- angular - 如何在 Jasmine 中测试 RxJs WebSocket
- python - 每 7 列后在热图中插入一行
- javascript - bcrypt 密码比较在带有 mongoose 的 Node.js 中不起作用
- javascript - 第一次在 Javascript 中使用类,我想知道如何在这段代码中添加一个 setInterval 以便我可以顺利移动 square(player1)