LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript】typeとinterfaceの違い

Last updated at Posted at 2021-09-29

TypeScriptのtypeinterfaceの違いをまとめています。

結論

typeエイリアスは、複数の場所で使い回す型に名前をつける

interfaceは、オブジェクトや関数の構造を定義する。


具体的なtypeとinterfaceの違いは以下です。

①同名の宣言
typeは、同名のtypeを宣言するとエラー。
interfaceは、同名のinterfaceを宣言するとマージされる。
②継承
typeは、継承できない。
interfaceは、継承できる。

①同名の宣言

typeは同名のtypeを宣言できません。(エラーになる。)

type Person = {
  name: string
  age: number
}

type Person = {
  hight: number
}
//エラー

interfaceは同名のinterfaceが宣言されるとマージされる。

interface Person {
  name: string
  age: number
}

interface Person {
  hight: number
}
//Personにhightというプロパティが付け足される。

const taro: Person = {
  name: "taro",
  age: 20,
  hight: 170
}

上記の場合、Person型を付けたtaroオブジェクトにはnameagehightの3つのプロパティが必須になっています。

②継承

typeは継承できません。

interfacemは、extendsを使って継承できます。

interface Person {
  name: string
  age: number
}

interface Employee extends Person {
  occupation: string
}
//Personを継承したEmployee型を定義

const taro: Employee = {
  name: "taro",
  age: 20,
  occupation: "sales",
}


ちなみにtypeは継承はできませんが、交差型で新しい型を作ることはできます。

type Person = {
  name: string
  age: number
}

type Hobby = {
  hobby1: string
  hobby2: string
}

type Introduction = Person & Hobby
//交差型で新しい型を宣言

const taro: Introduction = {
  name: "taro",
  age: 20,
  hobby1: "tennis",
  hobby2: "shopping"
}

まとめ

typeもinterfaceも実際ほとんど同じように使えますが、違いは以下。

①同名の宣言
typeは、同名のtypeを宣言するとエラー。
interfaceは、同名のinterfaceを宣言するとマージされる。
②継承
typeは、継承できない。
interfaceは、継承できる。

interfaceの方が柔軟に型を変化させることができるので、推奨されている様子です。

ただ、「柔軟に変化」できる分、思わぬバグを生みやすいとも言えそうなのでtypeが劣るというわけではない。

結論、違いを理解した上で、状況に応じて適切に使い分けていきましょう。

今回は以上です!

0
0
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
0
0