4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】typeとinterfaceの違いを表解で解説する

Posted at

はじめに

TypeScriptの勉強をしている中で、typeとinterfaceの違いについてだいぶややこしいなと思ったので、備忘録としてまとめておきます。

登場背景

オブジェクトを作成する際に、下記のように型注釈としてそれぞれのプロパティを宣言するとなった場合、プロパティの数が増えていくにつれて、可読性が落ちてしまうといった問題がありました。そこで、その問題を解決するために、typeとinterfaceといったものが登場しました。

const student: {name: string, age: number, hobby: string} = {
    name: "Taro",
    age: 18,
    hobby: "soccer"
};
console.log(student.name); // "Taro"
console.log(student.age); // 18
console.log(student.hobby); // "soccer"

typeとinterfaceの定義

type

typeとは、型に名前をつけることができるエイリアスになっています。下記の例では、Userといった名前にて型の宣言を行ってくれます。

type User = {
  name: string,
  age: number,
  hobby: string
}
const student: User = {
    name: "Taro",
    age: 18,
    hobby: "soccer"
};
console.log(student.name); // "Taro"
console.log(student.age); // 18
console.log(student.hobby); // "soccer"

interface

typeと同様に、型に名前をつけることができ、かつオブジェクト構造に特化して定義した型となっています。

interface User {
  name: string,
  age: number,
  hobby: string
}
const student: User = {
    name: "Taro",
    age: 18,
    hobby: "soccer"
};
console.log(student.name); // "Taro"
console.log(student.age); // 18
console.log(student.hobby); // "soccer"

typeとinterfaceの違い

上記の説明では、typeとinterfaceに違いがないと感じるかもしれませんが、
大きく分けて3つの違いがあります。

内容 type interface
型の種類 オブジェクト型以外の型でも定義可能 オブジェクト型のみ
型のマージ ×
継承 ×

型の種類

  • type:オブジェクト型以外(union型,tuple型など)の宣言が可能
  • interface:オブジェクト型のみの宣言が可能
type.ts
// type:定義できる(union型)
type SupportLanguage = "jp" | "en" | "fr" | "it"
interface.ts
// interface:定義できない(union型)
interface SupportLanguage { "jp" | "en" | "fr" | "it" }

型のマージ

  • type:同名の型を宣言した場合、マージされない
  • interface:同名の型を宣言した場合、マージされる
type.ts
// type:マージできない(エラー発生)
type User = {
  name: string
}
type User = {
  age: number
}
interface.ts
// interface:マージできる
interface User {
  name: string
}
interface User {
  age: number
}

const student: User {
  name: "Taro",
  age: 18
}

継承

  • type:継承できないが、交差型では表現可能
  • interface:継承ができる
type.ts
type Name = {
  name: string;
};
type Age = {
  age: number;
};

// 交差型(intersection型)で表現可能
type Member = Name & Age;

const student: Member = {
  name: "Taro",
  age: 18
};
interface.ts
interface Name {
  name: string;
}

interface User extends Name {
  age: number;
}

const student: User = {
  name: "Taro",
  age: 18
};

最後に

本記事では、typeとinterfaceの違いについて解説しました。
かつてはinterfaceを使うことが多かったようですが、最近はtypeで十分に機能を賄えるようになったので、type派が多くなったようです。
自分も、実際にアプリ開発するときに使い分けることができればと思いました!

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?