交差型

交差型(Intersection Type)は、複数の型を合成してすべての条件を満たす型を作るために使います。
TypeScriptでは & 演算子を用いて定義します。


🧱 基本構文

type 型A = { ... };
type 型B = { ... };

type 合成型 = 型A & 型B;

🧪 使用例:複数のプロパティを合成

type HasId = { id: string };
type HasTimestamp = { createdAt: Date };

type Entity = HasId & HasTimestamp;

const item: Entity = {
  id: "abc123",
  createdAt: new Date()
};
  • EntityidcreatedAt の両方を持つ必要がある

⚙ クラスや関数の引数として使う

type Position = { x: number; y: number };
type Size = { width: number; height: number };

type Rectangle = Position & Size;

function printRect(rect: Rectangle): void {
  console.log(rect.x, rect.y, rect.width, rect.height);
}

const box: Rectangle = {
  x: 10,
  y: 20,
  width: 100,
  height: 50
};

💡 interface との併用も可能

interface WithMeta {
  createdBy: string;
}

type Shape = Rectangle & WithMeta;

const shape: Shape = {
  x: 0,
  y: 0,
  width: 50,
  height: 50,
  createdBy: "system"
};

🧩 注意点

  • 同名のプロパティがある場合
    • 型が一致する場合はマージされます。
    • 型が異なる場合型の互換性エラー
  • あくまで「すべての型を満たす複合型」を作る用途向け。
コメントを残す 0

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