0
0

More than 1 year has passed since last update.

interface・typeの違いと使い分け

Posted at

何気なくコードを書いていたので、この際きちんと調べ直したのでアウトプット。

違い

interface

オブジェクトとクラスの型のみ定義する

// object
interface User {
  id: string
  name: string
}
// class
class Mypage implements User {
  id: string = 'A001'
  name: string = 'メッセージ'
}

拡張の仕方

interface User {
  id: string
  name: string
}
interface User {
  age: number
}
class Mypage implements User {
  id: string = 'A001'
  name: string = 'メッセージ'
  age: number = 28 // ageがないとエラーになる
}

継承の仕方

interface User {
  id: string
  name: string
}
interface Employee extends User {
  type: 'full-time' | 'temporary'
}

type

type オブジェクトやクラス以外の型も定義できる(stringやnumberだけでなく、'青' '白'、union型、タプル型など)

type EmployeeType = 'full-time' | 'temporary'
const employee: EmployeeType = 'full-time'

拡張の仕方(同名のものを使って拡張はできないが、交差型で可能)

type EmployeeType = 'full-time' | 'temporary'
type EmployeeDepartment = 'sales' | 'financial'
type EmployeeInfo = EmployeeType & EmployeeDepartment

継承はできない

個人的な使い分け

結論:プロジェクトごとで決める。

  • interfaceでできることはおおよそtypeでもでき、複数の型定義ができる。
  • interfaceで同一の型が定義されていた場合、意図しない拡張がされてしまう。
  • 実際、開発に入っていてもtypeでの型定義が多く、React × TypeScriptの開発が多い。
    上記の理由から、個人的には指定がなければ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