はじめに
TypeScriptを勉強していて、interfaceとtypeというものに出会いました。パッと見た時にどちらもオブジェクトの型を指定するものなのかな?と思いました。今回は、それらがどういったものか調べまとめてみました。
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,
};
typeはinterfaceと違い、継承を行うことはできません。しかし、交差型を使って継承と似たようなことができます。
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のinterfaceとtypeの違いについてまとめてみました。状況や用途、開発のルールに従って、使い分けができるといいのかなと思いました。何かわかったことがあれば、追記しようと思います。