Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Props TypeScript Generic: Type Value from Array of Object

I’m trying to build a custom Select component in React, the item list is sent via props.options (array of objects), since the object structure will vary, I need to define a key to access the value of props.options (items) via props.config. keyOfValue as well as labels.

I have tried using the code below but typescript is complaining. How to fix this problem.

function ReactSelect<T, K extends keyof T>(
  props: PropsWithChildren<{
    options: T[];
    value?: T[K];
    config: { keyOfValue: K; keyOfLabel: K };
  }>
) {
  // Type 'K' cannot be used to index type 'T[]'.ts(2536)
  const value = props.options[props.config.keyOfValue]; 

  // Type 'K' cannot be used to index type 'T[]'.ts(2536)
  const label = props.options[props.config.keyOfLabel]; 

  return <></>;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The options prop is an array, you cannot access a regular array in object notation (like arr['foo']), but props.options[props.config.keyOfValue] means that you are doing just that.

Try

function ReactSelect<T, K extends keyof T>(
  props: PropsWithChildren<{
    options: T;  // <--------- no array brackets

If options really is an array of Ts, you will have to specify an element by index before accessing a value by key:

const ix:number = 0
const value = props.options[ix][props.config.keyOfValue];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading