Skip to content

Commit

Permalink
Improve explanation of DeepSignalt ype
Browse files Browse the repository at this point in the history
  • Loading branch information
luisherranz committed Jan 15, 2024
1 parent d54aa54 commit 79cf9df
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 5 deletions.
38 changes: 33 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, boolean> };

const state = deepSignal<State>({ 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<State["map"]> = { 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<Store>({ counter: 0 });
```ts
state.map = newMap as DeepSignal<typeof newMap>;
```

```ts
state.map = { someKey: true } as DeepSignal<State["map"]>;
```

### RevertDeepSignal
Expand Down
35 changes: 35 additions & 0 deletions packages/deepsignal/core/test/types.ts
Original file line number Diff line number Diff line change
@@ -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 }]);
Expand Down Expand Up @@ -106,3 +107,37 @@ const store4 = deepSignal<Store4>({
store4.a.$b;
// @ts-expect-error
store4.c.$b;

// Manual typings
type Store5 = {
a: { b: number };
c: { b: number };
};
const store5 = deepSignal<Store5>({
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<Store5>({
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;

0 comments on commit 79cf9df

Please sign in to comment.