LoginSignup
7
5

More than 5 years have passed since last update.

ReactコンポーネントのPropsの型定義でジェネリクスを使う

Posted at

ジェネリクスを使ってReactコンポーネントの呼び出し元から型情報を渡す。

interface IProps<T> {
  a: T;
}

class A<T> extends React.PureComponent<IProps<T>> {
  render() {
    const { a } = this.props;
    return <p>{a}</p>;
  }
}

ReactDOM.render(
  <div>
    {/* 型推論 */}
    <A a="hoge" />

    {/* 型を明示 */}
    <A<string> a="hoge" />

    {/* 型エラー */}
    {/* <A<number> a="hoge" /> */}
  </div>,
  document.getElementById('app')
);

こっちの方が実用的っぽい👇

interface IProps<T> {
  onClick: T & React.MouseEventHandler<HTMLButtonElement>;
}

class Button<T> extends React.PureComponent<IProps<T>> {
  render() {
    const { onClick } = this.props;
    return (
      <button onClick={onClick}>click</button>
    );
  }
}

interface IClick1 { (): void; }
interface IClick2 { (): string; }

const click = () => {
  console.log('hoge');
};

ReactDOM.render(
  <div>
    {/* 型推論 */}
    <Button onClick={click} />

    {/* 型を明示 */}
    <Button<IClick1> onClick={click} />

    {/* 型エラー */}
    {/* <Button<IClick2> onClick={click} /> */}
  </div>,
  document.getElementById('app')
);

もともとはanyを使いたくなくてやり方を調べてたけど、型を明示するならまだしも型推論でなんでも通ってしまうのはanyと変わらない気もする🤔

こういう外からコールバック関数を渡したいときの型定義のべすとぷらくちすが知りたい。

7
5
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
7
5