インターフェース(interface)と `implements`

インターフェース(interface) は、オブジェクトの構造(プロパティやメソッド)を定義するための型です。
implements は、クラスがそのインターフェースの契約を満たすことを明示的に表すキーワードです。


✅ interface の基本構文

interface User {
  id: number;
  name: string;
  greet(): void;
}
  • プロパティやメソッドの構造のみを定義
  • 実装(中身)は持たない(あくまで「約束」)

🔗 implements:クラスでの使用

class Person implements User {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  greet() {
    console.log(`Hello, I'm ${this.name}`);
  }
}
  • implements によって User の契約(型)を満たす必要がある
  • プロパティ・メソッドをすべて正しく実装しないとコンパイルエラー

🛡️ interface を使うメリット

特徴 説明
✅ 構造的な型定義 「この形を持っていればOK」という柔軟な型
✅ クラスと連携しやすい implements で契約を保証できる
✅ 複数インターフェースの継承が可能 extends で合成できる
✅ 関数・オブジェクト・クラスに使える 幅広く使えるユーティリティ型

🔁 複数のインターフェースを implements

interface Identifiable {
  id: number;
}

interface Nameable {
  name: string;
}

class Member implements Identifiable, Nameable {
  constructor(public id: number, public name: string) {}
}

🧩 interface は関数にも使える

interface Greeter {
  (name: string): string;
}

const hello: Greeter = (name) => `Hello, ${name}`;

コメントを残す 0

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