🔖

React×Typescript Eventの型まとめ

2021/08/11に公開

event:any を避けたい!

まずはダメな例です

const onClick = (event: any) => {
    //処理
  };

tsを書くならany型は避けたいですよね

便利な型推論

なので、以下を使うのが便利です

type Props = {
  onClick: (event: React.MouseEvent<HTMLInputElement>) => void
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void
  onkeypress: (event: React.KeyboardEvent<HTMLInputElement>) => void
  onBlur: (event: React.FocusEvent<HTMLInputElement>) => void
  onFocus: (event: React.FocusEvent<HTMLInputElement>) => void
  onSubmit: (event: React.FormEvent<HTMLFormElement>) => void
  onClickDiv: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
}

使い方

const onClick = (event: React.MouseEvent<HTMLInputElement>) => {
    //処理
  };

Discussion