2-1. Type AliasとUnion型

型に名前をつける方法と複数の型を許容する方法を学びます

JS/TS基礎 - 第2章: TypeScript基礎 - 関数と配列・オブジェクト

課題:Type AliasとUnion型を使ってみよう

Type Aliasで型に名前をつけて再利用できます。 Union型を使うと「AまたはB」という柔軟な型定義ができます。

やること

  1. 1.User という名前のType Aliasを定義(name: stringage: number
  2. 2.User 型の変数 user1 を作成(名前: "太郎"、年齢: 25
  3. 3.Union型 Status を定義("active" | "inactive" | "pending"
  4. 4.Status 型の変数 currentStatus を作成(値: "active"
  5. 5.作成した変数を print() で表示

Type Aliasの書き方

// Type Aliasを定義
type Person = {
  name: string;
  age: number;
};

// 使用する
const person: Person = {
  name: "花子",
  age: 30
};

Union型の書き方

// Union型を定義(| で区切る)
type Result = "success" | "error" | "loading";

// 使用する
const status: Result = "success";

※ ヒント:Type Aliasは type キーワードを使います。 Union型は |(パイプ)で区切ります。

期待される出力

{"name":"太郎","age":25}
active
// ヘルパー関数(変更不要)
function print(value: any): void {
  const output = document.getElementById('output');
  if (output) {
    const div = document.createElement('div');
    div.style.margin = '8px 0';
    div.style.fontFamily = 'monospace';
    div.textContent = typeof value === 'object' ? JSON.stringify(value) : String(value);
    output.appendChild(div);
  }
}

// ここからあなたのコードを書いてください!

// 1. User型を定義


// 2. User型の変数user1を作成


// 3. Status型を定義(Union型)


// 4. Status型の変数currentStatusを作成


// 5. 表示