ngrx/signals: Add Store generic type
Closed this issue ยท 3 comments
Which @ngrx/* package(s) are relevant/related to the feature request?
signals
Information
I run in a situation in which I need the store type inside of the store declaration, so I cannot use InstanceType<typeof MyStore>
as this requires the instance to have been already created.
I created a stackblitz with a minimal store to picture the issue, but I think this could potentially happen in many other situations.
Could you please create a generic type for a Store that doesn't require the store instance to have been previously created?
Note: check this discussion for further details.
Describe any alternatives/workarounds you're currently using
I'm just using any
for the store type.
I would be willing to submit a PR to fix this issue
- Yes
- No
You can use WritableStateSource
for this case.
The example in the stackblitz can be updated to:
const asyncSearch = (searchService: SearchService, store: WritableStateSource<{ example: boolean }>) =>
rxMethod<string>(tap((query) => patchState(store, { example: true })));
// This could just return a regular function instead of using rxMethod, but it makes typings consistent compared to the asyncSearch method.
const syncSearch = (store: WritableStateSource<{ example: boolean }>) =>
rxMethod<string>(tap((query) => patchState(store, { example: true })));
As Tim mentioned, the type for the state source is already part of the public API. If you need the type for state signals, you can use the StateSignals
type. Here is an example:
import { patchState, StateSignals, WritableStateSource } from '@ngrx/signals';
type MyState = { foo: string; bar: number };
type MyStoreInstance = WritableStateSource<MyState> & StateSignals<MyState>;
function doSomething(store: MyStoreInstance): void {
console.log(store.foo());
console.log(store.bar());
patchState(store, { bar: 10 });
}
The type of methods and computed signals can also be specified:
type MyStoreInstance = WritableStateSource<MyState>
& StateSignals<MyState>
& { log(): void; count: Signal<number> };
Hello! are these public apis in 17.X version? or available only on 18.x?
In 17.X I see StateSignal
(I don't think is the same than StateSignals
) and no track of WritableStateSource