はじめてのTypeScriptプログラミング入門 30日コース | TypeScriptの核心「型」 - Day 15:Type Alias

30日で身につけるTypeScript
スポンサーリンク
スポンサーリンク

Day 15:Type Aliasで「型に名前をつける」感覚を身につける

第3週は、いよいよTypeScriptの核心である「型」に踏み込んでいく週です。 Day 15のテーマは Type Alias(型エイリアス)、つまり「型に名前をつけて再利用する」ことです。

学習内容は次のとおりです。

  • type
  • 型に名前を付ける
  • 型の再利用
  • Object Type

実践として、次の5つの型を作っていきます。

  • User
  • Product
  • Order
  • Customer
  • Address

ひとつひとつ、初心者の方にもイメージしやすいように、ステップバイステップで解説していきます。

Type Aliasとは:型に「ラベル」を貼るイメージ

なぜ型に名前をつけるのか

TypeScriptでは、次のように「その場で型を書く」ことができます。

const user = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
};
TypeScript

この user の型は、

{
  id: number;
  name: string;
  email: string;
}
TypeScript

と表現できますが、毎回この形をそのまま書いていると、だんだん大変になってきます。

そこで登場するのが Type Alias(型エイリアス)です。

// User型に名前をつける
type User = {
  id: number;
  name: string;
  email: string;
};
TypeScript

こうしておくと、

const user: User = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
};
TypeScript

のように、User という名前で型を再利用できるようになります。

基本構文:typeで型に名前をつける

Type Aliasの書き方

Type Aliasの基本構文はとてもシンプルです。

type 型の名前 = 型の定義;
TypeScript

Object Typeの場合は、次のようになります。

type User = {
  id: number;
  name: string;
  email: string;
};
TypeScript
  • type キーワードで「型に名前をつけます」。
  • User が「型の名前」です。
  • { ... } の中が「型の中身(プロパティとその型)」です。

この「型に名前をつける」感覚は、今後のTypeScript学習の土台になるので、ここでしっかり慣れておくと後が楽になります。

実践1:User型を作る

User型の設計

まずは、アプリでよく登場する「ユーザー」を表す User 型を作ります。 ここでは、次のような情報を持つユーザーを想定します。

  • id: ユーザーID(数値)
  • name: 名前(文字列)
  • email: メールアドレス(文字列)
  • isActive: 有効ユーザーかどうか(真偽値)
// ユーザーを表す型
type User = {
  id: number;        // ユーザーID
  name: string;      // 名前
  email: string;     // メールアドレス
  isActive: boolean; // 有効ユーザーかどうか
};

// User型を使った変数
const user1: User = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
  isActive: true,
};
TypeScript

重要ポイント:

  • User 型を定義しておくことで、「ユーザーオブジェクトの形」が明確になります。
  • user1: User と書くことで、「この変数はUser型である」と宣言できます。
  • プロパティ名のスペルミスや、型の間違いをコンパイル時に検出できるようになります。

実践2:Product型を作る

Product型の設計

次に、前の週でも登場した「商品」を表す Product 型を作ります。 ここでは、次のような情報を持つ商品を想定します。

  • id: 商品ID(数値)
  • name: 商品名(文字列)
  • price: 価格(数値)
  • stock: 在庫数(数値)
// 商品を表す型
type Product = {
  id: number;      // 商品ID
  name: string;    // 商品名
  price: number;   // 価格
  stock: number;   // 在庫数
};

// Product型を使った変数
const product1: Product = {
  id: 100,
  name: "ノートPC",
  price: 120000,
  stock: 5,
};
TypeScript

ポイント:

  • Product 型を定義しておくことで、商品管理プログラムなどで何度も再利用できます。
  • 「商品は必ず id, name, price, stock を持つ」というルールを、型として表現できます。

実践3:Address型を作る(ネストの準備)

Address型の設計

Customer や Order には、住所情報がよく登場します。 そこで、住所を表す Address 型を先に作っておきます。

ここでは、次のような情報を持つ住所を想定します。

  • postalCode: 郵便番号(文字列)
  • prefecture: 都道府県(文字列)
  • city: 市区町村(文字列)
  • street: 番地・建物名など(文字列)
// 住所を表す型
type Address = {
  postalCode: string; // 郵便番号
  prefecture: string; // 都道府県
  city: string;       // 市区町村
  street: string;     // 番地・建物名など
};

// Address型を使った変数
const address1: Address = {
  postalCode: "150-0002",
  prefecture: "東京都",
  city: "渋谷区",
  street: "渋谷2-21-1",
};
TypeScript

重要ポイント:

  • 住所のような「まとまった情報」は、1つの型として切り出しておくと再利用しやすくなります。
  • このあと作る Customer や Order の中で、Address 型を「ネスト」して使うことができます。

実践4:Customer型を作る(Addressをネストする)

Customer型の設計

Customer は、「顧客」を表す型です。 ここでは、次のような情報を持つ顧客を想定します。

  • id: 顧客ID(数値)
  • name: 顧客名(文字列)
  • email: メールアドレス(文字列)
  • address: 住所(Address 型)
// 顧客を表す型
type Customer = {
  id: number;      // 顧客ID
  name: string;    // 顧客名
  email: string;   // メールアドレス
  address: Address; // 住所(Address型をネスト)
};

// Customer型を使った変数
const customer1: Customer = {
  id: 10,
  name: "Hanako",
  email: "[email protected]",
  address: {
    postalCode: "150-0001",
    prefecture: "東京都",
    city: "渋谷区",
    street: "神宮前1-1-1",
  },
};
TypeScript

深掘りポイント:

  • address: Address; のように書くことで、「顧客の住所はAddress型である」と宣言できます。
  • これにより、「住所の形」が Customer の中でも一貫して使われます。
  • ネストされたObject Typeを使うことで、現実世界の構造をそのままコードに落とし込むことができます。

実践5:Order型を作る(複数の型を組み合わせる)

Order型の設計

最後に、「注文」を表す Order 型を作ります。 注文には、次のような情報が含まれることが多いです。

  • id: 注文ID(数値)
  • customer: 顧客情報(Customer 型)
  • products: 注文された商品一覧(Product 型の配列)
  • totalPrice: 合計金額(数値)
// 注文を表す型
type Order = {
  id: number;          // 注文ID
  customer: Customer;  // 顧客情報
  products: Product[]; // 注文された商品一覧
  totalPrice: number;  // 合計金額
};

// Order型を使った変数
const order1: Order = {
  id: 1000,
  customer: customer1, // 先ほど定義した customer1 を再利用
  products: [
    product1, // 先ほど定義した product1 を再利用
    {
      id: 101,
      name: "マウス",
      price: 2000,
      stock: 50,
    },
  ],
  totalPrice: 122000,
};
TypeScript

重要ポイント(ここはしっかり深掘り):

  • Order 型は、Customer 型と Product 型を組み合わせて作られています。
  • products: Product[]; のように書くことで、「注文された商品はProduct型の配列である」と宣言できます。
  • Type Aliasを使うと、「型を部品として組み合わせる」ことができ、複雑なデータ構造も整理して表現できます。

5つの型をまとめた練習テンプレート

最後に、今日作った5つの型をひとつのファイルにまとめた練習テンプレートを載せます。 このままコピーして、プロパティを増やしたり、関数を追加したりしながら、自分なりの「型設計」を試してみてください。

// day15-type-alias.ts
// Day 15:Type Alias 練習テンプレート

// 1. User型
type User = {
  id: number;
  name: string;
  email: string;
  isActive: boolean;
};

const user1: User = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
  isActive: true,
};

// 2. Product型
type Product = {
  id: number;
  name: string;
  price: number;
  stock: number;
};

const product1: Product = {
  id: 100,
  name: "ノートPC",
  price: 120000,
  stock: 5,
};

// 3. Address型
type Address = {
  postalCode: string;
  prefecture: string;
  city: string;
  street: string;
};

const address1: Address = {
  postalCode: "150-0002",
  prefecture: "東京都",
  city: "渋谷区",
  street: "渋谷2-21-1",
};

// 4. Customer型
type Customer = {
  id: number;
  name: string;
  email: string;
  address: Address;
};

const customer1: Customer = {
  id: 10,
  name: "Hanako",
  email: "[email protected]",
  address: {
    postalCode: "150-0001",
    prefecture: "東京都",
    city: "渋谷区",
    street: "神宮前1-1-1",
  },
};

// 5. Order型
type Order = {
  id: number;
  customer: Customer;
  products: Product[];
  totalPrice: number;
};

const order1: Order = {
  id: 1000,
  customer: customer1,
  products: [
    product1,
    {
      id: 101,
      name: "マウス",
      price: 2000,
      stock: 50,
    },
  ],
  totalPrice: 122000,
};

console.log("User:", user1);
console.log("Product:", product1);
console.log("Address:", address1);
console.log("Customer:", customer1);
console.log("Order:", order1);
TypeScript

Day 15のまとめ

Day 15では、

  • type キーワードで「型に名前をつける」Type Aliasの基本
  • Object Typeを使って、現実世界の情報(ユーザー・商品・住所・顧客・注文)を型として表現する方法
  • User / Product / Address / Customer / Order の5つの型を、部品として組み合わせて設計する流れ

を、具体的なコードとともに体験しました。

Type Aliasは、TypeScriptで本格的なアプリケーションを作るときに、ほぼ必ず使う重要な機能です。 ぜひ、プロパティを増やしたり、Optionalな項目を追加したりしながら、自分なりの「型の設計」を楽しんでみてください。型に名前をつけていくうちに、コード全体の構造がぐっと見通しよくなっていくはずです。


Day 15:Type Aliasで「型に名前をつける」練習を重ねる

第3週は、TypeScriptの核心である「型」をじっくり育てていく週です。 Day 15の演習テーマは Type Alias(型エイリアス)を5種類以上作ることです。

学習内容は次のとおりです。

  • type
  • 型に名前を付ける
  • 型の再利用
  • Object Type

ここでは、シンプルな型から少し複雑なObject Typeまで、ステップを踏みながら5種類以上のType Aliasを作っていきます。

Type Aliasの基本:型に「名前のラベル」を貼る

なぜ型に名前をつけるのか

TypeScriptでは、次のように「その場で型を書く」ことができます。

// その場で型を書く例
const user = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
};
TypeScript

この user の型は、

{
  id: number;
  name: string;
  email: string;
}
TypeScript

と表現できますが、毎回この形をそのまま書いていると、だんだん大変になってきます。

そこで登場するのが Type Alias(型エイリアス)です。

// User型に名前をつける
type User = {
  id: number;
  name: string;
  email: string;
};
TypeScript

こうしておくと、

const user1: User = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
};
TypeScript

のように、User という名前で型を再利用できるようになります。

ステップ1:シンプルなType Aliasで感覚をつかむ

まずは、Object Typeの前に、シンプルな型に名前をつける練習をしてみます。

// 数値IDを表す型
type ID = number;

// メールアドレス文字列を表す型
type Email = string;

// ユーザーのステータスを表す型(文字列の候補を限定)
type UserStatus = "active" | "inactive" | "banned";

// 使ってみる
const userId: ID = 1;
const userEmail: Email = "[email protected]";
const status: UserStatus = "active"; // "banned" などもOK

// status = "deleted"; // これはエラー(定義していない文字列)
TypeScript

重要ポイント:

  • type ID = number; のように、プリミティブ型にも名前をつけられます。
  • UserStatus のように、文字列の候補を限定することで、「ありえない値」を防ぐことができます。
  • こうした「小さな型の名前付け」が、後でObject Typeを組み合わせるときに効いてきます。

ステップ2:User型を作る(基本的なObject Type)

User型の設計

まずは、アプリでよく登場する「ユーザー」を表す User 型を作ります。

// ユーザーを表す型
type User = {
  id: ID;            // ユーザーID(ID型を再利用)
  name: string;      // 名前
  email: Email;      // メールアドレス(Email型を再利用)
  status: UserStatus; // ステータス(UserStatus型を再利用)
};

// User型を使った変数
const user1: User = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
  status: "active",
};
TypeScript

深掘りポイント:

  • User 型の中で、先ほど作った ID / Email / UserStatus を再利用しています。
  • これにより、「IDは必ず数値」「メールは文字列」「ステータスは決められた文字列だけ」というルールを、型として表現できます。
  • Type Aliasは「型を部品化して組み合わせる」ための道具だとイメージすると、設計が楽しくなります。

ステップ3:Product型を作る(シンプルな業務データ)

Product型の設計

次に、「商品」を表す Product 型を作ります。

// 商品を表す型
type Product = {
  id: ID;          // 商品ID
  name: string;    // 商品名
  price: number;   // 価格
  stock: number;   // 在庫数
};

// Product型を使った変数
const product1: Product = {
  id: 100,
  name: "ノートPC",
  price: 120000,
  stock: 5,
};
TypeScript

ポイント:

  • Product 型は、前週の「商品管理プログラム」とも相性がよい形です。
  • id: ID; のように、IDの型を統一しておくと、アプリ全体で「IDは数値」というルールが一貫します。

ステップ4:Address型を作る(ネストの準備)

Address型の設計

住所のような「まとまった情報」は、1つの型として切り出しておくと再利用しやすくなります。

// 住所を表す型
type Address = {
  postalCode: string; // 郵便番号
  prefecture: string; // 都道府県
  city: string;       // 市区町村
  street: string;     // 番地・建物名など
};

// Address型を使った変数
const address1: Address = {
  postalCode: "150-0002",
  prefecture: "東京都",
  city: "渋谷区",
  street: "渋谷2-21-1",
};
TypeScript

重要ポイント:

  • 住所を1つの型にまとめておくことで、User や Customer、Order など、複数の型から再利用できます。
  • 「住所の形」が変わったときも、Address 型だけ直せばよいので、メンテナンス性が上がります。

ステップ5:Customer型を作る(Addressをネストする)

Customer型の設計

顧客を表す Customer 型を作り、そこに Address をネストしてみます。

// 顧客を表す型
type Customer = {
  id: ID;          // 顧客ID
  name: string;    // 顧客名
  email: Email;    // メールアドレス
  address: Address; // 住所(Address型をネスト)
};

// Customer型を使った変数
const customer1: Customer = {
  id: 10,
  name: "Hanako",
  email: "[email protected]",
  address: {
    postalCode: "150-0001",
    prefecture: "東京都",
    city: "渋谷区",
    street: "神宮前1-1-1",
  },
};
TypeScript

深掘りポイント:

  • address: Address; のように書くことで、「顧客の住所はAddress型である」と宣言できます。
  • ネストされたObject Typeを使うことで、現実世界の構造をそのままコードに落とし込むことができます。
  • ここまでで、ID / Email / UserStatus / User / Product / Address / Customer と、すでに7種類のType Aliasが登場しています。

ステップ6:Order型を作る(複数の型を組み合わせる)

Order型の設計

最後に、「注文」を表す Order 型を作ります。 ここでは、次のような情報を持つ注文を想定します。

  • id: 注文ID(ID 型)
  • customer: 顧客情報(Customer 型)
  • products: 注文された商品一覧(Product 型の配列)
  • totalPrice: 合計金額(数値)
// 注文を表す型
type Order = {
  id: ID;            // 注文ID
  customer: Customer; // 顧客情報
  products: Product[]; // 注文された商品一覧
  totalPrice: number;  // 合計金額
};

// Order型を使った変数
const order1: Order = {
  id: 1000,
  customer: customer1,
  products: [
    product1,
    {
      id: 101,
      name: "マウス",
      price: 2000,
      stock: 50,
    },
  ],
  totalPrice: 122000,
};
TypeScript

重要ポイント:

  • Order 型は、これまで作ってきた ID / Customer / Product を組み合わせて構成されています。
  • Type Aliasを使うと、「型を部品として組み合わせる」ことができ、複雑なデータ構造も整理して表現できます。
  • ここまでで、演習の条件「5種類以上のType Alias」は十分に満たされています。

Day 15 演習テンプレート:7種類のType Aliasをまとめる

最後に、今日作ったType Aliasをひとつのファイルにまとめた練習テンプレートを載せます。 このままコピーして、プロパティを増やしたり、Optionalな項目を追加したりしながら、自分なりの「型設計」を試してみてください。

// day15-type-alias-practice.ts
// Day 15:Type Alias 演習テンプレート

// 1. シンプルな型エイリアス
type ID = number;
type Email = string;
type UserStatus = "active" | "inactive" | "banned";

// 2. User型
type User = {
  id: ID;
  name: string;
  email: Email;
  status: UserStatus;
};

const user1: User = {
  id: 1,
  name: "Taro",
  email: "[email protected]",
  status: "active",
};

// 3. Product型
type Product = {
  id: ID;
  name: string;
  price: number;
  stock: number;
};

const product1: Product = {
  id: 100,
  name: "ノートPC",
  price: 120000,
  stock: 5,
};

// 4. Address型
type Address = {
  postalCode: string;
  prefecture: string;
  city: string;
  street: string;
};

const address1: Address = {
  postalCode: "150-0002",
  prefecture: "東京都",
  city: "渋谷区",
  street: "渋谷2-21-1",
};

// 5. Customer型
type Customer = {
  id: ID;
  name: string;
  email: Email;
  address: Address;
};

const customer1: Customer = {
  id: 10,
  name: "Hanako",
  email: "[email protected]",
  address: {
    postalCode: "150-0001",
    prefecture: "東京都",
    city: "渋谷区",
    street: "神宮前1-1-1",
  },
};

// 6. Order型
type Order = {
  id: ID;
  customer: Customer;
  products: Product[];
  totalPrice: number;
};

const order1: Order = {
  id: 1000,
  customer: customer1,
  products: [
    product1,
    {
      id: 101,
      name: "マウス",
      price: 2000,
      stock: 50,
    },
  ],
  totalPrice: 122000,
};

console.log("ID:",  user1.id);
console.log("User:", user1);
console.log("Product:", product1);
console.log("Address:", address1);
console.log("Customer:", customer1);
console.log("Order:", order1);
TypeScript

Day 15のまとめ

Day 15では、

  • type キーワードで「型に名前をつける」Type Aliasの基本
  • シンプルな型(ID / Email / UserStatus)に名前をつけて再利用する流れ
  • Object Typeとして User / Product / Address / Customer / Order を設計し、組み合わせて使う方法

を、具体的なコードとともに体験しました。

Type Aliasは、TypeScriptで本格的なアプリケーションを作るときに、ほぼ必ず使う重要な機能です。 ぜひ、プロパティを増やしたり、Optionalな項目(?)を追加したりしながら、自分なりの「型のコレクション」を育ててみてください。型に名前をつけていくうちに、コード全体の構造がぐっと見通しよくなっていくはずです。

タイトルとURLをコピーしました