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

Getting type of HTML element's attributes

I would like to create a React component in Typescript that has all the same attributes as the HTML <select> element.

How would I type this?

type Props = {
  label: string
} & HTMLSelectElementAttributes; // This one is wrong


function MySelect(props: Props) {

  return <label>{props.label}</label><select {...props}>
    <option value="A">A</option>
    <option value="B">B</option>
  </select>;

}

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 :

In a type-aware IDE like VSCode, if you hover over the <select, you’ll see:

React.DetailedHTMLProps<React.SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>

You can use that as the type for the other props.

type Props = {
    label: string;
} & React.DetailedHTMLProps<React.SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>; // This one is wrong

const MySelect = (props: Props) => (
    <div>
        {' '}
        <label>
            label
            {props.label}
        </label>
        <select {...props} />
    </div>
);

// Example usage in which no type warnings result
const X = () => <MySelect label="foo" onChange={() => { console.log('change'); }} />;
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