ちゃんなるぶろぐ

エンジニア5年生🧑‍💻 オライリーとにらめっこする毎日。

【どっちが正解?】TypeScript論争〜type vs. interface〜

どうも、ちゃんなるです🐻

今回はTypeScriptのtypeinterfaceについて。

type vs. interface

筆者もどちらを使うかよく悩みます💦

実装のたびに悩むのはめんどくさい…

でも良質なコードを書きたくて、つい悩んでしまう…

そんな人の助けになりますように🙏

結論

どっちも便利、状況によって使い分けるべし!

シンプルにルール化するならば、

  • typeunionintersectionが必要になる場合に使う。

  • interfaceextendsimplementsを使いたい場合に使う。

以上。

実例

Union types

OR演算子(||)と似たイメージです👍

type A = {
  ...
}

type B = {
  ...
}

type C = A | B

(いい実例がなくてすみません笑)

Intersection types

AND演算子(&&)と似たイメージです👍

type Person = {
  name: string
  firstName: string
}

type Football = {
  club: string
}

type FootballPlayer = Person & Football

const example: FootballPlayer = {
  name: 'Mbappe',
  firstName: 'Kylian',
  club: 'Paris Saint-Germain'
}

Extends/Implements interfaces

interface Shape2d {
  x: number
  y: number
  ...
}

interface Shape3d extends Shape {
  z: number
  ...
}

class Circle implements Shape2d {
  ...
}

class Triangle implements Shape2d {
  ...
}

関連資料

www.typescriptlang.org

www.typescripttutorial.net

angularexperts.io

javascript.plainenglish.io