TypeScriptのInterfaceは、オブジェクトの構造を定義するための強力な機能です。この記事では、Interfaceの基本的な使い方から実践的なテクニックまでを詳しく解説します。
Interfaceの基本的な使い方
Interfaceは以下のように定義します:
interface User {
name: string;
age: number;
email: string;
}このInterfaceを使用してオブジェクトを作成する例:
const user: User = {
name: "John Doe",
age: 30,
email: "john@example.com"
};オプショナルプロパティの定義
すべてのプロパティが必須である必要はありません。`?`を使用してオプショナルプロパティを定義できます:
interface Profile {
name: string;
age?: number; // オプショナル
bio?: string; // オプショナル
}Interface の拡張
既存のInterfaceを拡張して新しいInterfaceを作成できます:
interface BasicUser {
name: string;
email: string;
}
interface AdminUser extends BasicUser {
permissions: string[];
role: 'admin';
}読み取り専用プロパティ
`readonly`修飾子を使用して、変更不可能なプロパティを定義できます:
interface Config {
readonly apiKey: string;
readonly endpoint: string;
}インデックスシグネチャ
動的なプロパティ名を持つオブジェクトを定義する場合:
interface Dictionary {
[key: string]: string;
}
const dict: Dictionary = {
"key1": "value1",
"key2": "value2"
};関数型の定義
Interfaceで関数の型も定義できます:
interface Calculator {
(x: number, y: number): number;
}
const add: Calculator = (a, b) => a + b;ベストプラクティス
1. 命名規則:Interfaceの名前は通常、大文字で始めます
2. 一貫性:関連するプロパティをグループ化します
3. 再利用:共通のプロパティは基本Interfaceとして抽出します
実践的な例
複雑なアプリケーションでの使用例:
interface BaseEntity {
id: number;
createdAt: Date;
updatedAt: Date;
}
interface Product extends BaseEntity {
name: string;
price: number;
description?: string;
category: Category;
}
interface Category {
id: number;
name: string;
products?: Product[];
}
// 使用例
const product: Product = {
id: 1,
name: "Laptop",
price: 999.99,
category: { id: 1, name: "Electronics" },
createdAt: new Date(),
updatedAt: new Date()
};よくある間違いと解決策
1. プロパティの型不一致
// 誤った使用
const user: User = {
name: "John",
age: "30", // エラー: numberが必要なところにstringを使用
};
// 正しい使用
const user: User = {
name: "John",
age: 30,
};2. 必須プロパティの欠落
// エラーを防ぐために全ての必須プロパティを含める
interface Required {
name: string;
age: number;
}
const person: Required = {
name: "John" // エラー: ageプロパティが欠落
};まとめ
TypeScriptのInterfaceは、型安全なコードを書くための基礎となる機能です。適切に使用することで、コードの品質と保守性を大きく向上させることができます。初心者から上級者まで、これらの概念を理解し実践することで、より堅牢なアプリケーションの開発が可能になります。