Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
How to create Type Alias from dynamic strings
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'.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!