🦁

【TypeScript勉強記】:(自分用)Type AliasとInterfaceの違い

2023/02/22に公開

学習素材

【日本一わかりやすいTypeScript入門】ハンズオンで理解するInterfaceとType Aliasの違い

Type AliasとInterfaceの誤読

Microsoftハンドブックでは、interfaceは拡張がしやすいのでなるべくinterfaceを使うよう記述しているが、以下のように誤読されやすい。

Because an interface more closely maps how JavaScript objects work by being open to extension, we recommend using an interface over a type alias when possible.

  • 型Alias(type)の方が機能が少ない
    • 大差なし
  • 全てのソフトウェアは拡張的であるべきなので、interfaceを使うべき
    • ライブラリ:不特定多数が利用するので拡張性を持つべき
    • アプリケーション:全ての型が拡張性を持っているとバグの原因になる

Interface

基本用法

interface宣言子で定義
Type Aliasと違い、「=」は不要

interface Bread {
  calories: number
}

宣言のマージ

宣言のマージとは、同じ名前を共有する複数の宣言を自動的に結合すること。
同名のinterfaceを宣言すると、型が追加(マージ)される

interface Bread {
  type: string
}

const francePan: Bread = {
  calories: 350,
  type: 'hard'
}

型エイリアスで表現する場合

宣言のマージを型エイリアスで表現する場合は、交差型を使う。

// 型エイリアスで表現
type MaboDofu = {
  calories: number,
  spicyLevel: number
}

type Rice = {
  calories: number,
  gram: number
}

// 交差型(Union)
type MaboDon = MaboDofu & Rice

const maboDon: MaboDon = {
  calories: 500,
  spicyLevel: 10,
  gram: 350
}

Interfaceの拡張

Interfaceは、extendsで継承したサブインターフェースを作成できる。

interface Book {
  page: number,
  title: string
}
// サブインターフェース
interface Magazine extends Book {
  cycle: 'daily' | 'weekly' | 'monthly' | 'yearly'
}

const jump: Magazine = {
  cycle: 'weekly',
  page: 300,
  title: '週刊少年ジャンプ'
}

また、interfaceは型エイリアスをextendsすることもできる。

type BookType = {
  page: number,
  title: string
}

interface Handbook extends BookType {
  theme: string
}

const cotrip: Handbook = {
  page: 120,
  title: 'ことリップ',
  theme: '旅行'
}

Interfaceでclassに型を定義する

implements(実装する)を使ってclassに型を定義できる

// implementsでclassに型を定義
class Comic implements Book {
  page: number
  title: string

  constructor(page: number, title: string, private publishYear: string) {
    this.page = page // 初期化で受け取ったpageを、このクラスのpageに代入する
    this.title = title // 初期化で受け取ったtitleを、このクラスのtitleに代入する
  }

  getPublishYear() {
    return this.title + "が発売されたのは" + this.publishYear + "年です。"
  }
}

const popularComic = new Comic(200, 'Demon Slayer', '2016')

Type AliasとInterfaceの違い

Type Alias Interface
用途 複数の場所で再利用する型に名前をつけるため オブジェクト、クラス、関数の構造を定義するため
拡張性 同名のtypeを宣言するとエラーになる 同名のinterfaceを宣言するとマージされる
継承 継承はできない。交差型で新しい型エイリアスを作る extendsによる拡張ができる
使用できる型 オブジェクトや関数以外のプリミティブ、配列、タプルも宣言可能 オブジェクトと関数の型のみ宣言可能
考慮事項 拡張しにくい不便さがある 拡張できることによりバグを生む可能性あり
いつ使う アプリ開発 ライブラリ開発

Discussion