0

I encountered an issue while trying to create a function to format options for dropdown.

This is the code in vanilla JS.

const formatOptions = (options, keyAsLabel, keyAsValue) => {
   return options.map(option) => {
    return {
      label: option[keyAsName],
      value: option[keyAsValue],
    }
   })
}

Currently, I have tried this code

const formatOptions = <T>(
  options: T[],
  keyAsLabel: T,
  keyAsValue: T
) => {
  return options.map((option, i) => {
    return {
      id: i + 1,
      label: option[keyAsLabel],
      value: option[keyAsValue],
    }
  })
}

But this code is giving error.

I want to make a strict type checking, but I have no idea how to make the second and the third parameter dependent on the first Parameter

1 Answer 1

2

Try using keyof:

const formatOptions = <T>(
  options: T[],
  keyAsLabel: keyof T,
  keyAsValue: keyof T
) => {
  return options.map((option, i) => {
    return {
      id: i + 1,
      label: option[keyAsLabel],
      value: option[keyAsValue],
    };
  });
};
Sign up to request clarification or add additional context in comments.

Comments

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.