Thomas
Thomas

Reputation: 4719

Typescript dictionary with dynamic keys

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);
            }
        });

Upvotes: 3

Views: 2347

Answers (1)

Yitzhak Barzilay
Yitzhak Barzilay

Reputation: 71

type storeType = {
    [key: string]: any // instead of any you can put any type you want...
}

now stores can have this:

const stores = {
    'userStore': 'anything',
    'listStore': 'anything'
}

console.log(stores.userStore) // will accept the type

Upvotes: 2

Related Questions