[signalStore] How to refer to the type of a particular store? #4140
-
How can I refer to the type of a particular store? E.g. if I want to pass the store as an argument into a function: type AuthState = { user: User | null };
export const AuthStore = signalStore(
{ providedIn: 'root' },
withState<AuthState>({ user: null })
);
const aHelperFunction = (store: ???) => {
// Here I want to be able to access `store.user()` (and anything else published by the store, like computed signals and methods).
} I've tried I suspect I'm missing some knowledge here on a) how the signal store is modelled (with an inner |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 17 replies
-
You can define the type of the SignalStore in the following way: // users.store.ts
export const UsersStore = signalStore(
withState({ users: [] as User[] })
);
export type UsersStore = InstanceType<typeof UsersStore>; Note: Exported type has the same name as the // 1) as a type:
import { UsersStore } from './users.store';
function doSomething(usersStore: UsersStore) {}
// 2) as a value:
import { UsersStore } from './users.store';
class UsersComponent {
readonly usersStore = inject(UsersStore);
}
// 3) type + value:
import { UsersStore } from './users.store';
@Component({
providers: [UsersStore], // value
})
class UsersComponent {
constructor(readonly usersStore: UsersStore) {} // type
} |
Beta Was this translation helpful? Give feedback.
-
Hi! This works well when the store instance has been created, but how could it be done before that, for example, if I need to access the store type from a function that returns an |
Beta Was this translation helpful? Give feedback.
You can define the type of the SignalStore in the following way:
Note: Exported type has the same name as the
UsersStore
constant. This is not required, but when defined like this, importedUsersStore
can be used as a type as well as value: