简体   繁体   English

Typescript 字典与动态键

[英]Typescript dictionary with dynamic keys

New to typescript and struggling to describe a dictionary. typescript 新手,难以描述字典。

Basically I export several stores (the example below is reduced on purpose), which I feed to a Registry class.基本上我导出了几个商店(下面的示例是故意减少的),我将它们提供给注册表 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.理想情况下,我希望商店字典类型是动态的,可以导出任意数量的商店,但是当我尝试在组件中使用注册表并尝试访问商店字典中不存在的内容时,TS 将抱怨,IDE 会接手。

Any TS wizardry will be much appreciated任何 TS 魔法将不胜感激

stores.ts商店.ts

import UserStore from './user.ts';
import ListStore from './list.ts';
export {
   UserStore, ListStore
};

registry.ts注册表.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);
        });
    }

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

now stores can have this:现在stores可以有这个:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM