0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[TypeScript]引数任意&&返り値の型固定な関数の型付けをしてみた

Last updated at Posted at 2022-01-04

前書き

ButtonコンポーネントのPropsとして、クリック時に発火する関数を受け取りたい
その関数は返り値はvoid固定だが、引数は任意にしたい
その関数の型はどう書けばよいか、すぐに出てこなかったため、その備忘録。

使用

  • TypeScript v4.5.4
  • React v17.0.2

書き方

type Props = {
  onClick: (...args: any[]) => void; // ← こちら
};

実装例

type Props = {
  label: string;
  onClick: (...args: any[]) => void;
};

export const Button = ({ label, onClick }: Props) => {
  return (
    <button onClick={onClick}>
      {label}
    </button>
  );
};

// 例えば、一方は引数なし、もう一方はidを引数に取るような関数を受け取る時
// 各データに依存するボタンなどは後者だと便利

const CardWithNoArgsButton = () => {
  const handleButton = () => {
    console.log('引数なし');
  };
  
  return (
    <div>
      <Button label="ボタンA" onClick={handleButton} />
    </div>
  );
};

const CardWithIdButton = () => {
  const handleButton = (id: string) => {
    console.log(`引数あり ${id}`);
  };
  
  return (
    <div>
      <Button label="ボタンB" onClick={handleButton} />
    </div>
  );
};

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?