【どっちが正解?】TypeScript論争〜type vs. interface〜
どうも、ちゃんなるです🐻
今回はTypeScriptのtypeとinterfaceについて。
筆者もどちらを使うかよく悩みます💦
実装のたびに悩むのはめんどくさい…
でも良質なコードを書きたくて、つい悩んでしまう…
そんな人の助けになりますように🙏
結論
どっちも便利、状況によって使い分けるべし!
シンプルにルール化するならば、
type
:union
やintersection
が必要になる場合に使う。interface
:extends
やimplements
を使いたい場合に使う。
以上。
実例
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 { ... }