どちらもデータの shape を記述するもので、しばしば交換可能ですが、異なる能力を持っています。
ts
interface User { name: string; age: number; }
type User2 = { name: string; age: number; };
どちらもデータの shape を記述するもので、しばしば交換可能ですが、異なる能力を持っています。
interface User { name: string; age: number; }
type User2 = { name: string; age: number; };
type にできて にできないことinterfacetype ID = string | number; // unions
type Pair = [number, number]; // tuples
type Name = User["name"]; // indexed/mapped/conditional types
type Nullable<T> = T | null; // wrap any type
type は あらゆる 型に対する汎用的な エイリアス です。プリミティブ、union、tuple、mapped type など。interface はオブジェクトや関数の shape のみを記述します。
interface にできて type にできないことinterface Box { width: number; }
interface Box { height: number; } // declaration merging — both merge into one
// Box now has width AND height
interface は declaration merging(複数の宣言が結合される)をサポートし、サードパーティ製ライブラリの型の拡張を含め、拡張/拡充するための慣用的な方法です。
interface Admin extends User { role: string; } // interface
type Admin2 = User & { role: string }; // type uses intersection
よくある慣習として、オブジェクトの shape や公開 API には interface(より良いエラーメッセージ、拡張可能、マージ可能)を使い、union、tuple、その他の型操作が必要なときは type を使います。一貫性のために、どちらかをデフォルトとして選んでください。多くのチームは、オブジェクトにはデフォルトで interface を使い、その追加の力が必要なときにだけ type に手を伸ばします。