2-2. Literal型とvoid型

特定の値を許可する型と戻り値がない関数の型を学びます

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

課題:Literal型とvoid型を使ってみよう

Literal型で特定の値だけを許可する型を作れます。 void型は戻り値がない関数に使います。

やること

  1. 1.Literal型 ButtonType を定義("primary" | "secondary" | "danger"
  2. 2.ButtonType 型の変数 btnType を作成(値: "primary"
  3. 3.void型を返す関数 showMessage を作成(引数: msg: string、処理: print(msg)を実行)
  4. 4.btnTypeshowMessage("Hello!") を実行

Literal型の書き方

// 特定の文字列だけを許可
type Size = "small" | "medium" | "large";

const mySize: Size = "medium";  // OK
// const mySize: Size = "tiny";  // エラー!

void型の書き方

// 戻り値がない関数
function greet(name: string): void {
  console.log(`Hello, ${name}!`);
  // returnしない
}

// アロー関数でも同じ
const sayGoodbye = (name: string): void => {
  console.log(`Goodbye, ${name}!`);
};

※ ヒント:Literal型は具体的な値を | で区切ります。 void型の関数は値を返しません。

期待される出力

primary
Hello!
// ヘルパー関数(変更不要)
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 = String(value);
    output.appendChild(div);
  }
}

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

// 1. ButtonType型を定義(Literal型)


// 2. ButtonType型の変数btnTypeを作成


// 3. void型を返す関数showMessageを作成


// 4. 実行