is not assignable to type(TS2322)のエラーが出た
Reactをやっていて、Propsの型定義の部分で〜is not assignable to type(TS2322)のエラーが発生したため、備忘録として残しておきたいと思います。
発生したエラー
以下が実際に発生したエラーです。
Type '(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void' is not assignable to type 'VoidFunction'. TS2322
エラーが出たコード
以下のコードでエラーが発生しました。
こちらがコンポーネント部分です。
ここのinterface PropsのfunctionProps: VoidFunctionの定義の部分でエラーが発生しています。
component.tsx
interface Props {
props1: propsType1,
props2: propsType2,
functionProps: VoidFunction
}
const Component: React.FC<Props> = { props1, props2, functionProps } => {
.
.
}
export default Component;
こちらのcontainer部分のfunctionPropsで、buttonClickFunctionを渡しています。
container.tsx
const buttonClickFunction = (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
.
.
};
<Component
props1={props1}
props2={props2}
functionProps={buttonClickFunction}
/>
エラー原因
エラー原因は、interface PropsのfunctionPropsの型が(event: React.MouseEvent) => voidと一致しないことによるものです。
解決方法
解決方法はエラーメッセージの通り、interface PropsのfunctionPropsの型がVoidFunctionになっているので、これを以下のように(event: React.MouseEvent) => voidに変えてやればOKです!
functionProps: (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => void;
修正後のコード
こちらがエラー修正後のコード全体になります。
component.tsx
interface Props {
props1: propsType1,
props2: propsType2,
functionProps: (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => void;
}
const Component: React.FC<Props> = { props1, props2, functionProps } => {
.
.
}
export default Component;
container.tsx
const buttonClickFunction = (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
.
.
};
<Component
props1={props1}
props2={props2}
functionProps={buttonClickFunction}
/>
参考サイト
こちらが参考サイトになります。
まとめ
今回は、Reactで〜is not assignable to type(TS2322)のエラー解決方法を掲載しました!
エラーの内容をちゃんと理解すれば解決方法は簡単でしたが、僕は少し迷ってしまったため、僕のように迷ってしまった方は是非参考にして頂ければと思います!
コメント