インターフェース
オブジェクトの構造と振る舞いを記述する抽象的な型です。具体的な実装を提供せず、継承可能(インターフェースはクラスと同様に継承できます)、オブジェクトの型チェックにも利用でき、複数のクラスで実装可能です。
オプションプロパティ
インターフェース内のプロパティは必須ではありません。非必須プロパティ名の後に"?"を追加するだけです。
export interface UserConfig {
userId: number; // 必須
userName?: string; // オプション
}
読み取り専用プロパティ
オブジェクト作成時にのみ値を設定でき、その後変更できません。プロパティ名の前に"readonly"を付けることで表現します。
interface Coordinate {
readonly x: number;
readonly y: number;
}
let point: Coordinate = { x: 15, y: 25 };
point.x = 8; // エラー発生!
インターフェースの役割1:オブジェクトの型チェック
export interface Product {
productId: number | string;
availability: boolean;
productName: string;
specifications?: any[];
subProducts?: Product[];
}
import { Product } from './product.ts';
const productList: Product[] = [
{ productId: 101, availability: true, productName: 'ノートパソコン' },
{productId:'202',availability:true,productName:'スマートフォン'}
];
インターフェースの役割2:継承
export interface Authentication {
username: string;
password: string;
emailAddress: string;
}
import { Authentication } from 'auth.ts';
export interface Customer extends Authentication {
customerId: number;
contactNumber?: string;
membershipLevel: string;
joinDate?: string;
}
// 複数インターフェースの継承例
interface Vehicle {
brand: string;
}
interface Engine {
horsepower: number;
}
interface Car extends Vehicle, Engine {
model: string;
year: number;
}
let myCar: Car = {};
myCar = { brand:'Toyota',horsepower:180,model:'Corolla',year:2023 };
console.log(myCar);
インターフェースの役割3:クラスによる実装
TypeScriptはクラスが特定の契約を満たすことを強制するためにインターフェースを利用できます。
複数のクラスに共通のプロパティがある場合、それらをインターフェースとして抽出し、implementsキーワードで実装します。この機能はオブジェクト指向プログラミングの柔軟性を大幅に向上させます。
クラスは他のクラスからしか継承できませんが、複数のインターフェースを実装できます。
// 2つのインターフェースを定義
interface Printable {
print(): void;
}
interface Scanable {
scan(): void;
}
// これらのインターフェースを実装するクラス
class OfficeDevice implements Printable, Scanable {
print() {
console.log('印刷中...');
}
scan() {
console.log('スキャン中...');
}
}
// インスタンスを作成してメソッドを呼び出す
const device = new OfficeDevice();
device.print(); // 出力: 印刷中...
device.scan(); // 出力: スキャン中...
interface TimerInterface {
currentTime: Date;
}
class Stopwatch implements TimerInterface {
currentTime: Date;
constructor(hour: number, minute: number) { }
}