【问题标题】:Dexie Real Class With TypeScript 3: Put/Add With undefined id Not Working使用 TypeScript 3 的 Dexie 真实类:使用未定义的 id 放置/添加不起作用
【发布时间】:2021-01-19 08:28:03
【问题描述】:

首先,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

对此有任何提示吗?

不幸的是,它在代码和框中工作:https://codesandbox.io/s/determined-lake-ntbzv?fontsize=14&hidenavigation=1&theme=dark

与codesandbox 相比,我不知道我的源代码中还有什么问题。可能是版本问题?不过 Dexie 版本是一样的。

【问题讨论】:

    标签: typescript dexie


    【解决方案1】:

    这个问题是关于打字稿的差异,因为编写了 Dexie 示例。将 id 属性声明为可选或带有感叹号以绕过。我会尝试更新文档。

    运行时错误是由于 ecmascript 类字段提案设置为处理类字段的方式。这也是新的,但已经在 chrome 中实现,当 typescript 转换为 esnext 时,它会让类字段保留。一个解决方法存在于将进入下一个 Dexie 版本的 PR 中。虽然还没有出来。该修复程序可能会进入版本 3.0.4。我会在这个 stackoverflow 问题可用时发表评论。

    【讨论】:

    • 我意识到修复这个问题的 PR 没有进入 dexie 3.0.3-rc.1。所以我刚刚更新了答案,它可能会进入3.0.4版本。
    猜你喜欢
    • 2013-01-25
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多