TypeScriptでinterfaceを定義する方法【サンプルコード付き】
- 作成日 2021.01.12
- 更新日 2026.06.12
- TypeScript
- TypeScript
TypeScriptでinterfaceを使用する方法を解説します。interfaceの基本的な定義方法、オプションプロパティ、readonly、extends、implementsの使い方、typeとの違いまでサンプルコード付きでわかりやすく紹介します。
環境
- OS windows10 64bit
- typescript Version 4.1.2
interfaceを使用
typescriptでは、以下のようにしてinterfaceを使用することが可能です。
interface hoge {
num: number;
str: string;
}
const h: hoge = { num: 10, str: 'mebee' }
console.log(h.num) // 10
console.log(h.str) // mebee「?」を付けて、省略することも可能です。
interface hoge {
num: number;
str?: string;
}
const h: hoge = { num: 10 }
console.log(h.num) // 10
const h2: hoge = { num: 10, str: 'mebee' }
console.log(h2.num) // 10
console.log(h2.str) // mebee関数も定義することが可能です。
interface hoge {
(num: number): number;
}
const h: hoge = (num) => num + num;
console.log(h(1)) // 2また、interfaceで設計にされたクラスを実装することも可能です。
interface iperson {
name:string;
Age:number;
getName():string;
getAge():number;
}
class person implements iperson{
public name:string;
public Age:number;
constructor(_name:string, _Age:number){
this.name = _name;
this.Age = _Age;
}
public getName(){ return this.name; }
public getAge(){ return this.Age; }
}
const p:person = new person('tom', 20);
console.log( p.getName()); // tom
console.log( p.getAge()); // 20
補足
TypeScriptのinterfaceは、オブジェクトの構造を定義するための機能です。複数のオブジェクトで同じプロパティを利用する場合に、型定義を共通化できるため、保守性の高いコードを書くことができます。
また、interfaceではオプションプロパティや読み取り専用プロパティも定義できます。
interface User {
readonly id: number;
name: string;
age?: number;
}?を付与すると省略可能なプロパティとなり、readonlyを付与すると値の変更を防ぐことができます。
さらに、複数のinterfaceを継承して利用することも可能です。
interface Person {
name: string;
}
interface Employee extends Person {
department: string;
}大規模な開発では、オブジェクトの構造を明確に定義できるinterfaceを活用することで、型安全性の向上やコードの可読性向上につながります。
参考リンク
関連記事
-
前の記事
C# 文字列の一部を抽出する 2021.01.11
-
次の記事
javascript 画像を切り抜いて表示する 2021.01.12
コメントを書く