jakearchibald / idb

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

IDBPTransaction TxStores type checking support #288

Open kabalage opened 1 year ago

kabalage commented 1 year ago

Is your feature request related to a problem? Please describe.

The transaction object returned by db.transation(['foo', 'bar', 'baz'], 'readwrite') has the type IDBPTransaction<MyDb, ('foo' | 'bar' | 'baz')[], 'readwrite'>

I would like to pass this transaction object to a function that accepts transactions that can manage the store 'foo'. Is this possible to check statically with TypeScript or do I have to use runtime checking?

In #200 there's an example that uses tuples:

const action = (t: IDBPTransaction<TestDBSchema, ['store1'], "readwrite">) => {
  t.store.clear()
}

But this does not work: Type '["foo"]' does not satisfy the constraint 'ArrayLike<"foo" | "bar" | "baz">'.

Describe the solution you'd like

It would be nice if something like this would work, but I can't figure out if it's currently possible:

async function add(
  entry: Entry,
  tx: IDBPTransaction<MyDb, StoresWithFoo, 'readwrite'>
) {
  const fooStore = tx.objectStore('foo');
  // use fooStore...
}
indianakernick commented 1 year ago

This can be achieved with generics.

function add<S extends StoreNames<Schema>>(
  tx: IDBPTransaction<Schema, ('foo' | S)[], 'readwrite'>
) {
  const foo = tx.objectStore('foo');
  // ...
}

The add function will accept a transaction that includes the foo object store plus any other object stores from the schema.