简体   繁体   中英

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

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 T s, 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM