New to typescript and struggling to describe a dictionary.
Basically I export several stores (the example below is reduced on purpose), which I feed to a Registry class.
Ideally the stores dictionary type I would like to be dynamic in a way that I can export as many stores I want, but when I try to use the registry in my component and try to access something that is not in the stores dict, TS will complain and the IDE will pick it up.
Any TS wizardry will be much appreciated
stores.ts
import UserStore from './user.ts';
import ListStore from './list.ts';
export {
UserStore, ListStore
};
registry.ts
export default class Registry{
stores = {};
constructor(stores: any){
Object.keys(stores).forEach((name: string) => {
const cls = stores[name];
this.stores[name] = new cls(this);
});
}
UPDATE based on the answer provided below. I changed the registry to this. All stores derive from BaseStore. However, I don't get TS complaining when I try to access a non existent store
export default class Registry{
stores: { [name: string]: BaseStore } = {};
constructor(stores: any){
Object.keys(stores).forEach((name: string) => {
const cls = stores[name];
if(cls){
this.stores[name] = new cls(this);
}
});
Storesubclasses? A link to a minimal, reproducible example on TS Playground would be helpful.