TypeScriptにおけるtype
TypeScriptでは、typeキーワードを使用して、単一の型キーワードでは表現できない複雑な型を定義します。typeキーワードは、より複雑な型宣言の別名を提供し、より簡潔で読みやすいコードを可能にします。
以下は、TypeScriptでtypeを使用する例です。
type Point = {
x: number;
y: number;
};
この例では、2次元平面上の座標を表すPoint型を定義しています。
TypeScriptにおけるinterface
TypeScriptにおけるinterfaceは、オブジェクトの特定の構造の契約を定義する方法です。インターフェースは主にオブジェクトの構造を定義するためや、クラス間の継承のために使用されます。
以下は、TypeScriptでinterfaceを使用する例です。
interface Point {
x: number;
y: number;
}
型の例と同様に、2次元平面上の座標を表すPointインターフェースを定義しています。
typeとinterfaceの違い
typeとinterfaceは、プログラム内で新しい型を定義するための基本的な構造ですが、微妙に異なる方法で動作し、異なるタイプの問題に適しています。
宣言のマージ
一つの主な違いは、interfaceはマージ可能であるが、typeはマージできないという点です。TypeScriptでは、同じインターフェースを複数回宣言した場合、宣言は1つのinterfaceに結合されます。
interface Foo {
x: number;
}
interface Foo {
y: number;
}
// Foo is now { x: number; y: number; }
typeでは同じ操作は重複した識別子エラーになります。
type Bar = {
x: number;
};
type Bar = {
y: number;
};
// Error: Duplicate identifier 'Bar'.
拡張と実装
interfaceは他のinterfaceを拡張したり、他のinterfaceから拡張されたりすることができます。また、interfaceはクラスによって実装されることもあります。これは、クラスの実装におけるコードの契約形式を提供することができます。
interface A {
x: number;
}
interface B extends A {
y: number;
}
class MyClass implements B {
x = 5;
y = 10;
}
一方、typeは他のtypeを拡張したり交差させたりすることができますが、クラスによって実装することはできません。
type C = {
x: number;
};
type D = C & {
y: number;
};
// This won't work
class MyOtherClass implements D {
x = 5;
y = 10;
}
// Error: Class 'MyOtherClass' incorrectly implements interface 'D'.
// Property 'x' is missing in type 'MyOtherClass' but required in type 'D'.
プリミティブ型との使用
typeキーワードは、string、number、boolean、null、undefinedなどのプリミティブ型を表現することができます。一方、interfaceはオブジェクト型の形状を表すために使用されます。
type MyString = string;
type NullableNumber = number | null;
計算プロパティ
typeエイリアスは計算されたプロパティを持つことができますが、interfaceはできません。
type ComputedType = {
[P in 'x' | 'y']: number;
};
// This is invalid for interfaces
interface ComputedInterface {
[P in 'x' | 'y']: number;
}
// Error: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
リテラル型
typeエイリアスはリテラル型を表現することができますが、interfaceではできません。
type Direction = 'North' | 'East' | 'South' | 'West';