LoginSignup
1
0

More than 1 year has passed since last update.

【TypeScript】interfaceとtypeの違い メモ

Posted at

interfaceとtypeの違いとは?

interfacetypeは両方とも型の定義に使用されますが、それぞれ異なる目的で使用されます。

interface

interfaceは主にオブジェクトの形状を定義するために使用されます。
例としてPersonオブジェクトを定義してみます。

interface Person {
  name: string;
  age: number;
  address?: string;
}

Personオブジェクトにはname,age,addressプロパティが存在します。
使用する際は以下の様にできます。

const yamada: Person = {
  name: "yamda";
  age: 20;
  address?: "tokyo";
}

type

typeは主に特定の方を再利用するために使用されます。
例としてAgeという方を定義してみます。

type Age = number;

例えば以下のような関数がある場合、コードの可読性が向上します。
また、変更を加えやすくなります。

function calculateBirthYear(currentYear: number, age: Age) {
  return currentYear - age;
}

agenumberでなければなりませんが、Age型を使うことで変数名や関数名の意図を明確にすることができます。

サバイバルTypeScriptの同様の記事はこちら↓
https://typescriptbook.jp/reference/object-oriented/interface/interface-vs-type-alias

1
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
1
0