1
0

TypeScript interface/type比較早見表

Last updated at Posted at 2024-08-25

概要

今回はTypeScriptのinterfacetypeを比較してみました。
どっちの方が優れているといった話ではないのでご容赦ください。

違いについて

早見表

特徴 interface type
基本目的 オブジェクトの形状を定義 型に名前を付ける(オブジェクト、プリミティブ、ユニオンなど)
拡張 extendsを使って拡張可能 &を使って交差型で合成可能
再オープン(マージ) 可能 不可能
プリミティブ型 使用不可 使用可能
ユニオン型 使用不可 使用可能
交差型 使用不可 使用可能
柔軟性 オブジェクト型に特化 非常に柔軟(関数型、タプル型、ユニオン型なども定義可能)

個人的な認識としてinterfaceはオブジェクトの定義typeは型に対して名前をつける行為だと思っているので、そういった思想でも使い分けができると良いのかなと思っています。

拡張

interface
interface A {
  name: string;
}

interface B extends A {
  power: number;
}

const test: B = { name: "a", power: 1 };
type
type A = {
  name: string;
};

type B = A & {
  power: number;
};

const test: B = { name: "a", power: 1 };

再オープン

interface
interface A {
  name: string;
}

interface A {
  power: number;
}

const test: A = { name: "a", power: 1 };

type
type A = {
  name: string;
};

// エラー
type A = {
  power: string;
};

const test: A = { name: "a", power: 1 };

プリミティブ型/ユニオン型/交差型

type
// プリミティブ型
type A = string;
type B = number;

// ユニオン型;
type C = string | boolean;
type D = B | C;
type E = 100 | "aaa" | true;

交差型は拡張で書いたので省略。

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