2-4. タプル型を理解する

useStateの型、複数値を返す関数の型を学びます

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

課題:タプル型を理解しよう

タプル型は、固定された長さと型を持つ配列です。 ReactのuseStateの戻り値もタプル型です。

やること

  1. 1.座標を表すタプル position を作る(型: [number, number]、値: [10, 20]
  2. 2.ユーザー情報のタプル user を作る(型: [string, number, boolean]、値: ["太郎", 25, true]
  3. 3.各タプルの要素を取り出して、print()で表示する

タプル型の書き方

タプル型は配列の各要素の型を個別に指定します:

// [型1, 型2, 型3] という形式
const point: [number, number] = [10, 20];
const info: [string, number] = ["太郎", 25];

タプルは通常の配列と違い、要素の順序と型が固定されています:

const point: [number, number] = [10, 20];

// 要素にアクセス
const x = point[0];  // number型
const y = point[1];  // number型

print(x);  // 10
print(y);  // 20

※ Reactでの使用例:useStateはタプル型を返します。例:[state, setState]

期待される出力

10
20
太郎
25
true
// ヘルパー関数(変更不要)
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. 座標を表すタプル position(型: [number, number])


// 2. ユーザー情報のタプル user(型: [string, number, boolean])


// 3. 各タプルの要素を取り出して表示