propsに型をつける

React + TypeScriptでは、props(プロパティ)に型を定義することで、コードの安全性・保守性・開発体験が大幅に向上します。

このドキュメントでは、関数コンポーネントにおけるpropsの型定義方法を基本から実践的な形式まで順に解説します。


1. 基本構文:Props型を定義して使う

type Props = {
  title: string;
  count: number;
};

const Header = ({ title, count }: Props) => {
  return 
<h1>{title}({count}件)</h1>;
};
  • Propsという型を定義し、関数の引数に適用します。
  • titlestringcountnumber型として型安全に扱えます。

2. オブジェクトとしてpropsを受け取る場合

type Props = {
  name: string;
  age: number;
};

const Profile = (props: Props) => {
  return (

<div>

<p>{props.name}</p>

<p>{props.age}歳</p>
    </div>
  );
};

解説:

  • 分割代入せずに props.name, props.age としてアクセスしたい場合に便利です。

3. Optional(省略可能)なprops

? を使うことで、受け取りを省略可能(undefinedでも可)にできます。

type Props = {
  title?: string;
};

const Header = ({ title }: Props) => {
  return 
<h1>{title ?? "デフォルトタイトル"}</h1>;
};

4. childrenを含む型

子要素(タグ内の中身)を受け取る場合は React.ReactNode を使います。

type Props = {
  children: React.ReactNode;
};

const Container = ({ children }: Props) => {
  return <div className="box">{children}</div>;
};

5. 関数props(イベントなど)

関数をpropsとして渡すときも、引数と戻り値に型を明示できます。

type Props = {
  onClick: (id: number) => void;
};

const DeleteButton = ({ onClick }: Props) => {
  return <button onClick={() => onClick(42)}>削除</button>;
};

6. 型エイリアスとインターフェースの使い分け

type(型エイリアス)

type Props = {
  label: string;
};

interface(インターフェース)

interface Props {
  label: string;
}

どちらでも動作しますが、次のような場合に使い分けられます:

特徴 type interface
拡張(extends) ✅ できる(交差型 & ✅ できる(継承)
ユニオン型 ✅ できる ❌ できない
Reactでは ✅ よく使われる(自由度高い) ✅ 特にchildren中心でよく使われる

このように、TypeScriptではpropsに明確な型を付けることで、IDE補完やバグ防止、ドキュメント性を高めることができます。

コメントを残す 0

Your email address will not be published. Required fields are marked *