获取 HTML 元素属性的类型

Getting type of HTML element's attributes

我想在 Typescript 中创建一个 React 组件,它具有与 HTML <select> 元素相同的所有属性。

我该如何输入?

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

}

在像 VSCode 这样的 type-aware IDE 中,如果您将鼠标悬停在 <select 上,您将看到:

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

您可以将其用作其他道具的类型。

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