はじめに
Typescriptにおける、interfaceと型エイリアスでの型定義の方法に関して、イマイチ違いがわからなかったので自己学習のためにもまとめてみました。
そもそも型定義って何(説明不要な方は飛ばしてください)
型定義とは、変数・関数・オブジェクトなどが持つべき型(データ形式・データ構造)を定義すること。
これにより、コード実行時のエラーを事前に検知したりコードの構造が明確になる
Typescriptでは、変数:型名の形で、型注釈(アノテーション)を付与します。
例
//変数
let age: number = 40;
//定数
const QUESTION: boolean = true;
//クラス
class Animal
name: string + '';
age: number = 0;
toString() : string {
return 'Person: ${this.name} (${this.age}歳)';
}
}
interfaceと型エイリアスの違いについて
基本的構造
//Interface
interface BookType {
title: string;
price: number;
}
let b: BookType = {
title: BOOK;
price: 500;
}
//型エイリアス
type BookType = {
title: string;
price: number;
}
let b: BookType = {
title: BOOK;
price: 500;
}
異なるポイント①:記述方法
interfaceは宣言なのに対して、typeは"="が必要。
//interface
interface BookType {
....//省略
}
//型エイリアス
type BookType = {
...//省略
};
異なるポイント②:宣言できる型
interface
オブジェクト・クラス等の型に特化して型を扱える
型エイリアス
プリミティブ型、関数型、タプル型、ユニオン型、インターセクション型など、様々な型を扱える
異なるポイント③:継承方法
//interfaceは継承を行える
interface BookType {
title: string;
}
type Paper = {
title: string;
};
interface FoodRecipe extends BookType, Paper {
foodType: string;
}
//型エイリアスは継承は行えないが、交差型(&)を用いることで、同じことが実現できる
type BookType = {
title: string;
}
type Paper = {
title: string;
};
type FoodRecipe = BookType &
Paper & {
foodType: string;
};
異なるポイント④:オーバーライド
//interfaceの場合は、継承元の型が上書きされる(元の型に代入できるものに限る)
interface BookType {
title: string;
price: number;
infomation: string;
}
interface MapBook {
title: string;
price: number;
tax: number;
}
interface MapBook {
title: string;
price: number;
tax: number;
ionformation: string;
}
//型エイリアスの場合は、継承元の型が上書きにはならず、型の交差型が計算される
type BookType = {
title: string;
price: number;
infomation: string;
}
type MapBook =BookType & {
title: number;
price: number;
tax: number;
}
type MapBook = {
title: never; //交差型を作成できないため、never型になる
price: number;
tax: number;
infomation: string;
}
異なるポイント⑤:同名のものを宣言
interface
同名のインターフェイスを定義でき、それらの定義をすべて合成したインターフェイスになる
型エイリアス
同名のものは複数定義できない
異なるポイント⑥:Mapped Types
interface
使用不可
型エイリアス
使用可
そもそもMapped Typesって何
→別で記事更新予定...
結論
必要に応じて適宜使い分けるのが良いが、どちらか迷ったら宣言できる表現の幅を考えると、まずは型エイリアスを使うのが良さそう。