type MenuName = 'menu1' | 'menu2';
const [menuState, setMenuState] = useState({
menu1: true,
menu2: false,
});
<SubMenu handleToggle={() => handleToggle('menu1')} name="Item1" />;
<SubMenu handleToggle={() => handleToggle('menu2')} name="Item2" />;
Now MenuName is hardcoded with menu1 and menu2, but I want to add in type dynamic values from an array like
const menus = [
{
name: 'menu1',
collapse: true,
},
{
name: 'menu2',
collapse: false,
},
];
in this case :
type MenuName = menus.map(item=>item.name).join('|');
is a error Cannot find namespace 'menus'.
I think this is what you want:
const menus = [
{
name: 'menu1',
collapse: true,
},
{
name: 'menu2',
collapse: false,
},
] as const;
type MenuName = typeof menus[number]['name'];
// type MenuName = "menu1" | "menu2"
Notice the const assertion, see that as const, it is a way of telling TypeScript that this array is not going to change. If you don't do so, it will set MenuName as string because it can be ever increasing array with any string value could possibly be menu name.
Playground Link: https://tsplay.dev/Wk5DlN