Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using random array strings to type object keys/properties - TypeScript

I would like to have a dynamic Array<string> that then makes a dynamic Object with the key/property from the array's values. (using for a prop usage in reactjs typescript)

here's an example code:

interface Props {
  buttons: Array<string>;
  buttonProps?: { [key: string]: string }; //want key here to correspond with values of buttons
}

I am guessing you use generics here but I am unsure on how to proceed with that.

like image 311
Jesse Avatar asked Oct 14 '25 06:10

Jesse


1 Answers

because key is string you have to add a generic, otherwise any string will be valid and it means you can put anything in buttons and in buttonProps.

I hope I got the question correctly.

interface Props<T extends keyof any = keyof any> {
  buttons: Array<T>;
  buttonProps?: { [key in T]: string };
};

const buttons: Props<'test1' | 'test2'> = {
  buttons: [
    'test1', 'test2',
  ],
  buttonProps: {
    test1: 'string1',
    test2: 'string2',
  },
};
like image 102
satanTime Avatar answered Oct 17 '25 00:10

satanTime