Dexie.js
Dexie.js copied to clipboard
Typescript shows $list from liveQuery as unknown
Looks like a possible bug with the types not being compatible with svelte store?
For example, this shows $todos being of type unknown
:
let todos = liveQuery(() => db.todos.toArray());
This is the workaround I had to use:
let todos: Todo[];
let todos_obs = liveQuery(() => db.todos.toArray());
$: todos = $todos_obs as Todo[];
Both work fine at runtime though.
This is using sveltekit and package.json has those in case that's relevant:
"svelte": "^3.46.0",
"svelte-preprocess": "^4.10.1",
"dexie": "^3.2.2"
Ok, thanks for sharing! The trick seems to be to patch dexie's typing for Observable<T>
to better comply with the typings of Svelte's Readable.
The following code in your global.d.ts
should do the trick:
/// <reference types="svelte" />
import { Subscriber, Unsubscriber } from 'svelte/store';
import { Subscription } from 'dexie';
declare module 'dexie' {
interface Observable<T> {
subscribe(run: Subscriber<T>): Unsubscriber | Subscription;
}
}
If you don't have a file global.d.ts, try create one inside the src folder.
I think that incorporating this code into dexie itself might mess up with its compability of RxJS. A future solution might be to offer a Svelte-dedicated version of liveQuery(). But for now, this should do it.
Yes, that works for me. Could this be in the release or should the svelte integration doc be updated to include this?
Yes, that works for me. Could this be in the release or should the svelte integration doc be updated to include this?
For now, I've added a reference from the Svelte-flavoured Getting Started page to this issue from its Typescript section.
I'll see if there's any way of supporting this in the typings without destroying the RX compability. It could also be that Svelte should support typings for observables better. I know that the Svelte Store contract explicitely allows the subscribe function to return a Subscription (ES Observable proposal + RX) rather than an Unsubscriber (Native Svelte) for the sake of RX interopability. So maybe it would be in Svelte's interest to let the typings work better.
Fair enough.
Perhaps this should be mentioned under Create a component that queries data
as a bullet point because people are likely to miss that above and be confused as to why copy / pasting that code sample would throw errors in their editors.
Alternatively, having the content of the global.d.ts
snippet under Using Typescript?
would make a lot of sense there. I think for now this will be required by everyone wanting to use dexie and svelte.
Note: The latest version of dexie@next (version 4.0.1-alpha.10) gives a bit better svelte and sveltekit support:
- Typings of Observables returned from liveQuery() is type-wise compatible with Svelte Readable
- No need to check for browser / SSR within your queries as the code executes fine on both server and browser
Closing this issue as it is solved in [email protected].