LoginSignup
56
31

More than 1 year has passed since last update.

【TypeScript】type派?interface派?僕はもちろんtype派

Last updated at Posted at 2021-09-16
1 / 17

TypeScript?


型付けできるJavaScript

let age: number = 0;

age = 28;

age = "ぞんぞん"; //エラー

いろんな型

意味
string 文字列 'ぞんぞん'
number 数値 28
boolean 真偽値 true
[] 配列 string[] → ['aaa', 'bbb', 'ccc']
any 制約なし

オブジェクトの型は?


普通に書くと読みづらい、管理しづらい🥺(ぱおん)

const miyazon: {name: string, age: number, department: string} = {
  name: "みやぞん",
  age: 28,
  department: "product"
}

interface vs type(型エイリアス)


オブジェクトの型指定にはinterfaceまたはtype(型エイリアス)を使う

interface

interface Employee {
  name: string;
  age: number;
  department: string;
}

const miyazon: Employee = {
  name: "みやぞん",
  age: 28,
  department: "product"
}

オブジェクトの型指定にはinterfaceまたはtype(型エイリアス)を使う

type(型エイリアス)

type Employee = {
  name: string;
  age: number;
  department: string;
}

const miyazon: Employee = {
  name: "みやぞん",
  age: 28,
  department: "product"
}

interfaceとtypeの違い

interface type
用途 クラス、オブジェクトの型定義 型に別名をつける
交差型, 共用体型, タプル型, マップ型 非対応 対応
同じ要素名の再宣言 拡張される できない

「用途の違い」を感じる(interface)

VS Codeなどで名前をホバーしたとき、型本来の情報を出してくれますが、ここで違いが出ます。
interfaceは型そのものなので名前が出ます。


「用途の違い」を感じる(type)

無名の型に別名を付けただけなので、本来の「無名の型」が表示されます。


「同じ要素名の再宣言」を感じる

typeでは再宣言した時点でエラーとなるがinterfaceではどうなる...?

interface Employee {
  name: string;
}

interface Employee {
  age: number;
}

interface Employee {
  department: string;
}

「同じ要素名の再宣言」を感じる

エラーにならない!

interface Employee {
  name: string;
}

interface Employee {
  age: number;
}

interface Employee {
  department: string;
}

const miyzon: Employee = {
  name: "ぞんぞん",
  age: 28,
  department: "product"
}

どっちを使う?

  • できることがtypeのほうが多い
  • interfaceの再宣言による拡張でバグが発生しうる

型にはまらない人間でありたいが、私はtypeを選びます。


「複業クラウド」について

弊社Another worksでは複業マッチングプラットフォーム「複業クラウド」を開発しています!

▼複業でスキルを活かしてみませんか?複業クラウドの登録はこちら!
https://talent.aw-anotherworks.com/?login_type=none

56
31
3

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
56
31