如何解决使用TypeScript 3的Dexie真实类3:使用未定义ID的放置/添加不起作用
首先,docs中的“真实类”示例无法编译:
export class Contact implements IContact {
id: number;
first: string;
last: string;
emails: IEmailAddress[];
phones: IPhoneNumber[];
constructor(first: string,last: string,id?:number) {
this.first = first;
this.last = last;
if (id) this.id = id;
}
编译器抱怨没有在构造函数中设置id。保留使ID为undefined
/ id?
的选项。
但是使用未定义的ID,Table.put()/add()
会引发错误:Unhandled Rejection (DataError): Data provided to an operation does not meet requirements.
我的示例代码:
export class DBProgram {
id?: number
name: string
description: string
constructor(name: string,description: string,id?:number) {
this.name = name
this.description = description
// if(id) this.id = id
}
save() {
return idb.transaction('rw',idb.dbPrograms,async () => {
// delete this.id
this.id = await idb.dbPrograms.add(this);
});
}
}
export class Idb extends Dexie {
dbPrograms: Table<DBProgram,number>
constructor () {
super("Idb")
this.version(1).stores({
dbPrograms: '++id,name,description,commands',})
this.dbPrograms = this.table('dbPrograms')
this.dbPrograms.mapToClass(DBProgram)
}
}
export const idb = new Idb()
当我取消注释delete this.id
时,它将运行并存储具有自动ID的对象。但是看来Dexie不会处理undefined
id
。
对此有任何提示吗?
不幸的是,它可以在codeandbox中使用:https://codesandbox.io/s/determined-lake-ntbzv?fontsize=14&hidenavigation=1&theme=dark
与codesandbox相比,我不知道源代码中仍然存在什么问题。也许是版本问题?不过,Dexie版本是相同的。
解决方法
此问题与打字稿的差异有关,因为编写了Dexie示例。将id属性声明为可选属性,或使用感叹号声明。我将尝试更新文档。
运行时错误是由于ecmascript类字段proposal设置为处理类字段引起的。这也是新的,但是已经在chrome中实现,当打字稿转换为esnext时,它将保留类字段。 PR中存在针对此问题的解决方法,它将在下一个Dexie版本中出现。还没出来该修复程序可能会进入3.0.4版。如果有可用的堆栈溢出问题,我将发表评论。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。