jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.2k stars 348 forks source link

delete only takes key as string but autoincremented keys are numbers #307

Closed primavera133 closed 4 months ago

primavera133 commented 4 months ago

I'm having some issues with types when trying to delete records in an IndexedDB, when using typescript and idb.

I'm setting up a database with autoincremented keys like:

interface MyDB {
   recordId ?: string
...
}

export let db: IDBPDatabase<MyDB>;

export const initDB = async () => {
db = await openDB<MyDB>(dbName, dbVersion, {
    upgrade(db) {
      const recordStore = db.createObjectStore("records", {
        keyPath: "recordId",
        autoIncrement: true,
      });
      recordStore.createIndex("by-date", "date");
    },
  });
}; 

Typescript only accepts type string for keys as input to the delete function:

const selectedKey: string = ...
await db.delete("records", selectedKey)

If I use number instead for recordId (which seems more correct) I will have to use .toString() or equivalent to make Typescript happy:

const selectedKey: number = ...
await db.delete("records", selectedKey.toString())

However, this doesn't work. No key is deleted!

I'm assuming in runtime keys are just numbers and not converting them to strings work (even if Typescript thinks the keys are strings in transpile-time)

primavera133 commented 4 months ago

I perhaps found the answer myself, I used the type IDBKeyRange instead and both Typescript and runtime code seems to work. Not entirely sure yet that it's correct use of that type...