useStateの型、複数値を返す関数の型を学びます
JS/TS基礎 - 第2章: TypeScript基礎 - 関数と配列・オブジェクト
タプル型は、固定された長さと型を持つ配列です。 ReactのuseStateの戻り値もタプル型です。
position を作る(型: [number, number]、値: [10, 20])user を作る(型: [string, number, boolean]、値: ["太郎", 25, true])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