diff --git a/README.md b/README.md index 5966541..063c764 100644 --- a/README.md +++ b/README.md @@ -560,16 +560,44 @@ DeepSignal exports two types, one to convert from a plain object/array to a `dee ### DeepSignal -You can use the `DeepSignal` type if you want to declare your type instead of inferring it. +You can use the `DeepSignal` type if you want to manually convert a type to a deep signal outside of the `deepSignal` function, but this is usually not required. + +One scenario where this could be useful is when doing external assignments. Imagine this case: + +```ts +import { deepSignal } from "deepsignal"; + +type State = { map: Record }; + +const state = deepSignal({ map: {} }); +``` + +If you want to assign a new object to `state.map`, TypeScript will complain because it expects a deep signal type, not a plain object one: + +```ts +const newMap: State["map"] = { someKey: true }; + +state.map = newMap; // This will fail because state.map expects a deep signal type. +``` + +You can use the `DeepSignal` type to convert a regular type into a deep signal one: ```ts import type { DeepSignal } from "deepsignal"; -type Store = DeepSignal<{ - counter: boolean; -}>; +const newMap: DeepSignal = { someKey: true }; + +state.map = newMap; // This is fine now. +``` + +You can also manually cast the type on the fly if you prefer: -const store = deepSignal({ counter: 0 }); +```ts +state.map = newMap as DeepSignal; +``` + +```ts +state.map = { someKey: true } as DeepSignal; ``` ### RevertDeepSignal diff --git a/packages/deepsignal/core/test/types.ts b/packages/deepsignal/core/test/types.ts index 69f98c9..a0eddcd 100644 --- a/packages/deepsignal/core/test/types.ts +++ b/packages/deepsignal/core/test/types.ts @@ -1,5 +1,6 @@ import { signal, Signal } from "@preact/signals-core"; import { deepSignal, peek, shallow } from "../src"; +import type { Shallow } from "../src"; // Arrays. const array = deepSignal([{ a: 1 }, { a: 2 }]); @@ -106,3 +107,37 @@ const store4 = deepSignal({ store4.a.$b; // @ts-expect-error store4.c.$b; + +// Manual typings +type Store5 = { + a: { b: number }; + c: { b: number }; +}; +const store5 = deepSignal({ + a: { b: 1 }, + c: { b: 1 }, +}); + +store5.a.b; +store5.a.$b; +store5.c.b; +store5.c.$b; +// @ts-expect-error +store5.d; + +type Store6 = { + [key: string]: { b: number }; +}; + +const store6 = deepSignal({ + a: { b: 1 }, + // @ts-expect-error + c: { b: "1" }, +}); + +store5.a.b; +store5.a.$b; +store5.c.b; +store5.c.$b; +// @ts-expect-error +store5.d;