Skip to content

Commit

Permalink
Expose the Shallow type for manual typings
Browse files Browse the repository at this point in the history
  • Loading branch information
luisherranz committed Jan 15, 2024
1 parent 71d8f9d commit d54aa54
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Use [Preact signals](https://github.com/preactjs/signals) with the interface of
- [TypeScript](#typescript)
- [`DeepSignal`](#deepsignal-1)
- [`RevertDeepSignal`](#revertdeepsignal)
- [`Shallow`](#shallow)
- [License](#license)

## Features
Expand Down Expand Up @@ -581,6 +582,24 @@ import type { RevertDeepSignal } from "deepsignal";
const values = Object.values(store as RevertDeepSignal<typeof store>);
```

### Shallow

You can use the `Shallow` type if you want to type a store that contains a shallow object.

```ts
import type { Shallow } from "deepsignal";

type Store = {
obj: { a: number };
shallowObj: { b: number };
};

const store = deepSignal<Store>({
obj: { a: 1 },
shallowObj: shallow({ b: 2 }),
});
```

## License

`MIT`, see the [LICENSE](./LICENSE) file.
Expand Down
6 changes: 4 additions & 2 deletions packages/deepsignal/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ export const peek = <
};

const isShallow = Symbol("shallow");
export function shallow<T extends object>(obj: T): T & { [isShallow]: true } {
export function shallow<T extends object>(obj: T): Shallow<T> {
ignore.add(obj);
return obj as T & { [isShallow]: true };
return obj as Shallow<T>;
}

const createProxy = (target: object, handlers: ProxyHandler<object>) => {
Expand Down Expand Up @@ -277,6 +277,8 @@ type DeepSignalArray<T> = DeepArray<ArrayType<T>> & {
$length?: Signal<number>;
};

export type Shallow<T extends object> = T & { [isShallow]: true };

export declare const useDeepSignal: <T extends object>(obj: T) => DeepSignal<T>;

type FilterSignals<K> = K extends `$${infer P}` ? never : K;
Expand Down
17 changes: 17 additions & 0 deletions packages/deepsignal/core/test/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,20 @@ store3.a = { b: 1 };
// @ts-expect-error
store3.c = { b: 2 };
store3.c = shallow({ b: 2 });

type Store4 = {
a: { b: number };
c: Shallow<{ b: number }>;
d: Shallow<{ b: number }>;
};

const store4 = deepSignal<Store4>({
a: { b: 1 },
c: shallow({ b: 2 }),
// @ts-expect-error
d: { b: 3 },
});

store4.a.$b;
// @ts-expect-error
store4.c.$b;

0 comments on commit d54aa54

Please sign in to comment.