Home > database >  React Props TypeScript Generic: Type Value from Array of Object
React Props TypeScript Generic: Type Value from Array of Object

Time:01-23

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 <></>;
}

CodePudding user response:

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];
  • Related