## 主な違い
[[インターフェース (TypeScript)|インターフェース]](interface)と[[型エイリアス (TypeScript)|型エイリアス]](type)の主な違い。
| 機能 | type | interface |
| --------------------------------------------- | ---------- | --------- |
| [[プロパティ (TypeScript)\|プロパティ]]の拡張 | ✅ | ✅ |
| 既存定義の拡張 (同名定義) | ❌ | ✅ マージ |
| 型の別名 | ✅ | ❌ |
| パフォーマンス | ❌良くない | ✅良い |
## 公式の見解
> For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use `interface` until you need to use features from `type`.
>
> *[Documentation - Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces)*
経験則としては **[[型エイリアス (TypeScript)|型エイリアス]]が必要になるまでは[[インターフェース (TypeScript)|インターフェース]]を使えばよい** とのこと。
## [[プロパティ (TypeScript)|プロパティ]]の拡張
### ✅[[インターフェース (TypeScript)|インターフェース]]の場合
[[extends (JavaScript)|extends]]で拡張できる。
```ts
interface Readable {
read(): void;
}
interface Writable extends Readable {
write(): void;
}
// declare const x: Writable;
// x.read();
// x.write();
```
### ✅[[型エイリアス (TypeScript)|型エイリアス]]の場合
[[交差型 (TypeScript)|交差型]]で拡張できる。
```ts
type Readable = {
read(): void;
};
type Writable = Readable & {
write(): void;
};
// declare const x: Writable;
// x.read();
// x.write();
```
## 既存定義の拡張
### ✅[[インターフェース (TypeScript)|インターフェース]]の場合
同名で再定義すると[[プロパティ (TypeScript)|プロパティ]]が拡張される。
```ts
interface Writable {
read(): void;
}
interface Writable {
write(): void;
}
// declare const x: Writable;
// x.read();
// x.write();
```
### ❌[[型エイリアス (TypeScript)|型エイリアス]]の場合
同名で再定義はできないのでエラーになる。
```ts
// Duplicate identifier 'Writable'. [2300]
type Writable = {
read(): void;
};
// Duplicate identifier 'Writable'. [2300]
type Writable = {
write(): void;
};
```
## 型の別名
### ❌[[インターフェース (TypeScript)|インターフェース]]の場合
型の別名は定義できない。
### ✅[[型エイリアス (TypeScript)|型エイリアス]]の場合
[[プリミティブ型 (JavaScript)|プリミティブ型]]、[[オブジェクト型 (TypeScript)|オブジェクト型]]も含めて型の別名を定義できる。他にも[[型エイリアス (TypeScript)|型エイリアス]]でしか表現できない型や型演算子が多数存在する。
```ts
// Primitive Types
type ID = string;
// Object Types
type Human = { id: number; name: string };
// Union Types
type Color = "red" | "green" | "blue";
// Intersection Types
type HumanDetail = Human & { color: Color };
```
## パフォーマンス
以下の観点で[[インターフェース (TypeScript)|インターフェース]]のほうが優れていることが多い。
- [[交差型よりインターフェースの継承を使用する (TypeScript)#型の関連がキャッシュされる]]
- [[交差型よりインターフェースの継承を使用する (TypeScript)#すべての構成要素を確認する必要がない]]