2-3. インターフェースを定義する

再利用可能なオブジェクトの型定義を学びます

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

課題:インターフェースを定義してみよう

インターフェースを使うと、オブジェクトの型を再利用可能な形で定義できます。 オプショナルプロパティを使えば、必須でないプロパティも表現できます。

やること

  1. 1.Product インターフェースを定義:
    • name: string(必須)
    • price: number(必須)
    • description?: string(オプショナル)
  2. 2.Product 型の変数 product1 を作成(name: "ノートPC"、price: 89800、description: "高性能"
  3. 3.Product 型の変数 product2 を作成(name: "マウス"、price: 2980、descriptionなし)
  4. 4.両方の商品情報を print() で表示

インターフェースの書き方

// インターフェースを定義
interface User {
  name: string;
  age: number;
  email?: string;  // ? でオプショナル
}

// 使用する
const user1: User = {
  name: "太郎",
  age: 25,
  email: "[email protected]"
};

const user2: User = {
  name: "花子",
  age: 30
  // emailは省略可能
};

※ ヒント:インターフェースは interface キーワードを使います。 オプショナルプロパティは ? をつけます。

期待される出力

{"name":"ノートPC","price":89800,"description":"高性能"}
{"name":"マウス","price":2980}
// ヘルパー関数(変更不要)
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. Productインターフェースを定義


// 2. product1を作成(descriptionあり)


// 3. product2を作成(descriptionなし)


// 4. 表示