Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IDBPTransaction TxStores type checking support #288

Open
kabalage opened this issue Dec 10, 2022 · 2 comments
Open

IDBPTransaction TxStores type checking support #288

kabalage opened this issue Dec 10, 2022 · 2 comments

Comments

@kabalage
Copy link

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
Copy link

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.

@Malien
Copy link

Malien commented Aug 17, 2024

Oh, thanks @indianakernick. Turns out 'foo' | S was the missing key in my case. Couldn't think, by myself, of how to require a transaction has selected at least the required store.

And there I sat, thinking I know a lot about TS type-wizardry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants