T
T
TheSnegok2022-04-05 11:00:26
typescript
TheSnegok, 2022-04-05 11:00:26

How to type an object whose keys are strings?

I tried to type an object, but it gives errors, tell me what is wrong and where can I find normal documentation on typing deep objects?:

interface NameItem {
    [key: string]: string;
    [key: string]: string;
}

interface MenuName {
    [key: string]: NameItem;
}

interface IMenuItem {
    [key: string]: MenuName;
}

const MenuItems: IMenuItem[] = [
    {
        "Плитка": {
            "Tile": '../../Image/hoverMenu/icon1.svg',
            "Ванны": ["Ванны 150 см", "Ванны 160 см", "Ванны 170 см", "Ещё"],
        }
    },
    {
        "Сантехника": {
            "Plumbing": '../../Image/hoverMenu/icon2.svg',
        }
    },
    {
        "Мебель для ванной": {
            "Bathroom Furniture": '../../Image/hoverMenu/icon3.svg',
        }
    },
    {
        "Электроника и бытовая техника": {
            "Electronics": '../../Image/hoverMenu/icon4.svg',
        }
    },
    {
        "Отопление": {
            "Heating": '../../Image/hoverMenu/icon5.svg',
        }
    },
    {
        "Напольное покрытие": {
            "Flooring": '../../Image/hoverMenu/icon6.svg',
        }
    },
];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bugs-bunny, 2022-04-05
@TheSnegok

interface NameItem {
    [key: string]: string;
    [key: string]: string; // - эту строку удалить, так как строка сверху уже указывает на произвольное количество ключей типа строка со значением строка
}

Well, if each NameItem can contain either a string or an array of strings, then you can also do this:
interface NameItem {
    [key: string]: string | Array<string>;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question