[TypeScript]interface

// Shape インターフェースの定義
interface Shape {
  color: string;
  getArea(): number; // メソッドの型のみ定義
  describe(): void;
}

// Circle クラス
class Circle implements Shape {
  constructor(public color: string, private radius: number) {}

  getArea(): number {
    return Math.PI * this.radius ** 2;
  }

  describe(): void {
    console.log(`This is a ${this.color} circle.`);
  }
}

// Rectangle クラス
class Rectangle implements Shape {
  constructor(public color: string, private width: number, private height: number) {}

  getArea(): number {
    return this.width * this.height;
  }

  describe(): void {
    console.log(`This is a ${this.color} rectangle.`);
  }
}

// インスタンス作成
const circle = new Circle("red", 10);
console.log(circle.getArea()); // 314.159...
circle.describe(); // This is a red circle.

const rectangle = new Rectangle("blue", 5, 8);
console.log(rectangle.getArea()); // 40
rectangle.describe(); // This is a blue rectangle.

特徴 interface abstract class
インスタンス化 不可 不可
プロパティ・メソッドの型定義 型のみ 型+実装
コンストラクタ なし あり
複数の継承 可能(多重継承OK) 不可能(単一継承のみ)

 

複数のinterfaceをimplementsするクラス

// 移動可能なオブジェクトのインターフェース
interface Movable {
  speed: number;
  move(): void;
}

// 描画可能なオブジェクトのインターフェース
interface Drawable {
  color: string;
  draw(): void;
}

// CarクラスがMovableとDrawableを両方実装
class Car implements Movable, Drawable {
  constructor(public speed: number, public color: string) {}

  move(): void {
    console.log(`The car is moving at ${this.speed} km/h.`);
  }

  draw(): void {
    console.log(`Drawing a ${this.color} car.`);
  }
}

// インスタンス作成
const myCar = new Car(100, "red");

myCar.move();  // The car is moving at 100 km/h.
myCar.draw();  // Drawing a red car.

 
オブジェクトに使用

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "Taro",
  age: 25,
};

console.log(user.name); // "Taro"
console.log(user.age);  // 25

interface User {
  name: string;
  age?: number; // ageは省略可能
}

const user1: User = { name: "Taro" }; // OK
const user2: User = { name: "Jiro", age: 30 }; // OK

 
関数に使用

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

const sayHello: Greeting = (name) => `Hello, ${name}!`;

console.log(sayHello("John")); // "Hello, John!"

 
配列に使用

interface NumberArray {
  [index: number]: number;
}

const numbers: NumberArray = [1, 2, 3, 4];

console.log(numbers[0]); // 1

 
キャストする

interface Car {
  brand: string;
  model: string;
}

const myCar = {
  brand: "Toyota",
  model: "Corolla",
  year: 2023, // 追加のプロパティ
} as Car; // `year`は無視される

console.log(myCar.brand); // "Toyota"
console.log(myCar.model); // "Corolla"