Dexie.js
Dexie.js copied to clipboard
Typescript: liveQuery() should return Observable<T | undefined>
The observable value from a liveQuery() is initially undefined and therefore undefined
should be included in the type. Otherwise, if we forget to wrap the usage of the observable in an if
block (or ?.
, ??
etc.), we receive a runtime error. This should really be enforced by types at compile time.
Example with svelte:
<script>
import { liveQuery } from "dexie";
import { db } from "./db";
const friends = liveQuery(() => db.friends.toArray());
</script>
<p>{$friends.length}</p> /* runtime error */
The returned observable actually never emits undefined - but Svelte's '$' operator will return undefined if the observable hasn't emitted any value yet. Svelte's documentation around this states that they do return undefined in case the store hasn't emitted any value, but normal Svelte stores will always emit values synchronously and having an asynchronous store may be a too specific case in the Svelte world to change their typings.