例えばスタイリングされたパーツのコンポーネントを作るとして、ある HTML 属性をプロップスで受け取るようにする場合、これまでは MDN のドキュメントを見て手打ち入力していました。
type Props = {
text: string;
type: "button" | "submit" | "reset";
};
export function StyledButton(props: Props) {
const { text, type } = props;
return <button type={type}>{text}</button>;
}
type Props = {
inputMode:
| "none"
| "text"
| "tel"
| "url"
| "email"
| "numeric"
| "decimal"
| "search";
};
export function StyledInput(props: Props) {
const { inputMode } = props;
return <input inputMode={inputMode} />;
}
これでも問題はないですが、属性が多くなる場合だと入力するのが面倒ですね。
JSX.IntrinsicElements #
JSX.IntrinsicElements
にこれらの型が定義されているため、それを利用すれば自分で入力する必要はありません。(ということを最近知りました)
type Props = {
text: string;
type: NonNullable<JSX.IntrinsicElements["button"]["type"]>;
};
export function StyledButton(props: Props) {
const { text, type } = props;
return <button type={type}>{text}</button>;
}
type Props = {
inputMode: NonNullable<JSX.IntrinsicElements["input"]["inputMode"]>;
};
export function StyledInput(props: Props) {
const { inputMode } = props;
return <input inputMode={inputMode} />;
}