型エイリアス(type定義)

TypeScript の type は、型に別名(エイリアス)を与える構文です。
複雑な型を再利用しやすくしたり、ユニオン型・タプル・ジェネリクスなど柔軟な構造を記述するのに使われます。


🏷 基本構文

type 型名 = 型定義;

例:

type UserId = string;
type Age = number;

📚 使用例:オブジェクト型に名前をつける

type User = {
  name: string;
  age: number;
};

const user: User = {
  name: "Hanako",
  age: 30
};

🔁 型の合成(交差型 &)

type HasId = { id: string };
type Timestamped = { createdAt: Date };

type Entity = HasId & Timestamped;

const item: Entity = {
  id: "abc123",
  createdAt: new Date()
};
  • & 演算子で型を合成(交差型 / intersection type)

⚡ ユニオン型との組み合わせ

type Status = "loading" | "success" | "error";

const state: Status = "success";
  • 値の選択肢を限定したいときに有効
  • リテラル型との相性が良い

✅ まとめ

  • type型に別名をつけるための柔軟な機能
  • ユニオン型、交差型、ジェネリック型に強い
  • オブジェクト構造中心なら interface、柔軟な型操作なら type が向いている
type Response = "ok" | "ng";

type を使えば、複雑な型も簡潔に再利用・共有できます。

コメントを残す 0

Your email address will not be published. Required fields are marked *