Dexie.js icon indicating copy to clipboard operation
Dexie.js copied to clipboard

Typescript: liveQuery() should return Observable<T | undefined>

Open jrouleau opened this issue 1 year ago • 1 comments

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 */

jrouleau avatar Jun 09 '23 21:06 jrouleau

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.

dfahlander avatar Jul 01 '23 23:07 dfahlander