From cb675fc96129ab057e1736654e10e80446b877e0 Mon Sep 17 00:00:00 2001 From: MCW77 <7250892+MCW77@users.noreply.github.com> Date: Sun, 31 May 2026 05:10:07 +0200 Subject: [PATCH] fix(State): add types to Lookup table example - The observable referencing itself mandates explicit typing - Selector needs narrower type to avoid typecheck error for indexing into possibly unavailable keys - Add imports, so the code could run after copy/paste --- docs/content/state/v3/usage/observable.mdx | 46 +++++++++++++++------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/docs/content/state/v3/usage/observable.mdx b/docs/content/state/v3/usage/observable.mdx index 5962840..d140938 100644 --- a/docs/content/state/v3/usage/observable.mdx +++ b/docs/content/state/v3/usage/observable.mdx @@ -355,25 +355,41 @@ state$.itemsReady[0].status.set('disabled') A function with a single `string` key can be used as a lookup table (an object with a string key). Accessing it by index will call the function to create a computed observable by that key. ```ts -const state$ = observable({ - selector: 'text', - items: { - test1: { text: 'hi', othertext: 'bye' }, - test2: { text: 'hello', othertext: 'goodbye' } - }, - // Return a link to the [selector] property in the given item - texts: (key: string) => { - return state$.items[key][state$.selector.get()] - }, -}) +import { + type Observable, + observable, +} from "@legendapp/state"; + +type Item = { + text: string; + othertext: string; +}; +type Items = Record; +type State = { + selector: keyof Item; + items: Items; + texts: (key: keyof State['items']) => Observable; +}; + +const state$: Observable = observable({ + selector: 'text', + items: { + test1: { text: 'hi', othertext: 'bye' }, + test2: { text: 'hello', othertext: 'goodbye' }, + }, + // Return a link to the [selector] property in the given item + texts: (key: keyof State['items']) => { + return state$.items[key][state$.selector.get()]; + }, +}); // Now these reference the same thing: -state$.items.test1.text.get() -state$.texts['test1'].get() +state$.items.test1.text.get(); +state$.texts['test1'].get(); // And setting a text goes through to the linked observable -state$.texts.test1.set('hello') -state$.items.test1.text.get() // 'hello' +state$.texts.test1.set('hello'); +state$.items.test1.text.get(); // 'hello' ``` ### event