Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
            }
        });
like image 818
Thomas Avatar asked Jan 20 '26 13:01

Thomas


1 Answers

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
like image 92
Yitzhak Barzilay Avatar answered Jan 22 '26 03:01

Yitzhak Barzilay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!