ReactでHTMLの要素をWrapしたComponentを作成する際に、Propsの型をよしなに定義してほしい。
React.ComponentProps
を使うと良いらしい。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import React from "react";
import style from "./Input.module.css";
type Props = Omit<React.ComponentProps<'input'>, 'className'>
export function Input(props: Props) {
return (
<input
{...props}
className={style.input}
/>
)
}
|
input
タグが受け付ける要素群を型として引っ張ってきたうえで、Component内で定義したい(親から渡されたくない) className
は TypeScriptの Omit
で除外している。
VSCode上で Props
にマウスオーバーすると、型定義が参照できる。

定義どおり、親からは name
などが渡せるが、除外した className
は渡せなくなっている。

StylingにCSS Modulesを使うのであれば、Input.modules.css
を配置しておくと
1
2
3
4
5
6
7
8
9
10
|
.input {
padding: 10px;
border: gray;
border-radius: 5px;
background-color: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
font-size: 16px;
transition: box-shadow 0.3s ease;
width: 300px;
}
|

Component内で独自に定義したStyleがあたったCustom Componentができた。