0

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

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I got the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.