Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

ReactのeventHandler関数の型を定義する

参考にさせていただいたページ

型定義と関数定義を別々にやる

たぶんこんな感じ

import { FocusEventHandler, ChangeEventHandler, CompositionEventHandler } from 'react';

type HandleBlur = FocusEventHandler<HTMLInputElement>;
type HandleChange = ChangeEventHandler<HTMLInputElement>;
type HandleComposition = CompositionEventHandler<HTMLInputElement>;

const handleBlur: HandleBlur = ({ target, type }) => {
  console.log(target);
  console.log(type);
};

const handleChange: HandleChange = ({ target, type }) => {
  console.log(target);
  console.log(type);
};

const handleComposition: HandleComposition = ({ target, type }) => {
  console.log(target);
  console.log(type);
};

関数定義するときに引数の型設定をまとめてやる

たぶんこんな感じ

import { CompositionEvent } from 'react';

const handleComposition = ({
  target,
  type,
}: CompositionEvent<HTMLInputElement>) => {
  void onChange({ target, type });
};