0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】typeとinterfaceの違い

Posted at

はじめに

実務で使っているコードで、typeとinterfaceがどちらも使われているのですが、どういう使い分けがされているんだろうと疑問を持ったのが調査のきっかけです。

typeの場合

type Human = {
  name: string;
  age: number;
};

let human1: Human = {
  name: "yamada",
  age: 20,
};

human1.age = "21" // これは型エラーとなる

型に名前をつけるみたいな感じですね。

interfaceの場合

interface Human {
  name: string;
  age: number;
}

let human1: Human = {
  name: "yamada",
  age: 20,
};

human1.age = "21" // 型エラーとなる

書き方がちょっと変わっただけで、typeとやっていることは一緒です。

じゃあ違いは何だ?

定義できる型の種類

interfaceだとオブジェクトとクラスの型だけ定義できるけど、typeでは他の型も定義できます。

type Animal = "トラ" | "ライオン" | "" | "";

let animal: Animal = "トラ";
animal = "ゾウ"; // ゾウはAnimal型には無いよと怒られます

ユニオン型みたいな形で定義もできます。

拡張できるかどうか

interfaceは拡張ができます。

interface Human {
  name: string;
}

interface Human {
  age: number;
}

const human: Human = {
  name: "tanaka",
  age: 20
};

const human2: Human = {
  name: "yamamoto"
}; // これだとageも指定しろと怒られます

再宣言ではなく、新しいプロパティの型定義を追加した形となっています。
ただ、typeでも&を用いることで、拡張のようなことはできるみたいです。

どちらを使うのが良いのか

interfaceは拡張性があるので、使いやすい気もしますが注意しないといけない点があります。

interface Person {
  tall: number;
  weight: number;
}

// 大量のコード

const person: Person = {
  tall: 170,
  weight: 60
}; // Property 'name' is missing in type '{ tall: number; weight: number; }' but required in type 'Person'

あれ、nameが必要だけどPersonにない…?と思ってコードを見てみると、

interface Person {
  name: string;
}

このようなコードが書かれていました。つまり、知らず知らずのうちに拡張されていたのです。

interfaceでできることはtypeでもできるようになったし、typeの方が定義できる型の範囲も広いので、とりあえず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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?