LoginSignup
6
1

More than 1 year has passed since last update.

TypeScriptのinterfaceとtypeについて調べてみた

Last updated at Posted at 2022-12-21

はじめに

TypeScriptを勉強していて、interfacetypeというものに出会いました。パッと見た時にどちらもオブジェクトの型を指定するものなのかな?と思いました。今回は、それらがどういったものか調べまとめてみました。

TypeScriptのinterfaceとtypeについて調べてみた

interfaceとは

interfaceは、オブジェクトやクラスの構造を定義するものです。以下のような感じで構造を定義できます。

interface Book {
    name: string;
    price: number;
}

const book: Book = {
    name: "book",
    price: 1000,
};

interfaceは、extendsキーワードを使ってinterfaceの継承を行うことができます。

interface Book {
    name: string;
    price: number;
}

interface Novel extends Book {
   category: string;
}

const novel: Novel = {
    name: "novel",
    price: 800,
    category: "mystery",
};

また、既に定義したinterfaceと同じ名前のものを宣言することができます。宣言後、既に定義されたものと後から宣言されたものはマージされます。

interface Animal {
    name: string;
}

interface Animal {
   classification: string;
}

const animal: Animal = {
    name: "animal",
    classification: "mammal",
}

typeとは

typeは、型エイリアスと呼ばれ、型に名前をつけることができます。interfaceと違い、オブジェクトやクラスの型を宣言するだけではなく、プリミティブ型などに名前をつけることができます。またこれに加えて、typeではunion型やtuple型を扱えるのもinterfaceと違うところです。

type Num = number;

type StringOrNull = string | null;

type Book = {
    name: string,
    price: number,
};

const book: Book = {
    name: "book",
    price: 1000,
};

typeinterfaceと違い、継承を行うことはできません。しかし、交差型を使って継承と似たようなことができます。

type Book = {
    name: string,
    price: number,
};

type Novel =  Book & {
   category: string,
};

 const novel: Novel = {
    name: "novel",
    price: 800,
    category: "mystery",
}; 

またinterfaceのように、既に宣言されたものと同じ名前を型エイリアスを宣言することはできません。

type Animal = {
    name: string,
};

type Animal = {
    classification: string,
};
// => ERROR

さいごに

今回は、TypeScriptのinterfacetypeの違いについてまとめてみました。状況や用途、開発のルールに従って、使い分けができるといいのかなと思いました。何かわかったことがあれば、追記しようと思います。

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