0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptのTuple型:初学者向けガイド

Posted at

TypeScriptの基本:Tuple型の理解と活用

TypeScriptを使い始めると、すぐに登場するのが「Tuple型」です。Tuple型は配列に似ていますが、より具体的に定義されています。この記事では、Tuple型について基本から実用的な使い方までを紹介します。

Tuple型とは?

Tuple型は、特定の数と型の順序で要素を持つ配列です。配列とは異なり、Tupleは各要素の型と順序が決まっています。

Tuple型の基本

定義方法

Tuple型は、各要素の型を順番に指定して定義します。

let exampleTuple: [number, string];
exampleTuple = [42, "Hello"]; // OK
exampleTuple = ["Hello", 42]; // エラー: 順序が違います

要素のアクセス

Tupleの要素にはインデックスでアクセスします。

let person: [string, number];
person = ["Alice", 30];

console.log(person[0]); // "Alice"
console.log(person[1]); // 30

要素の変更

要素の変更も可能ですが、指定された型を守る必要があります。

let person: [string, number];
person = ["Alice", 30];

person[0] = "Bob";  // OK
person[1] = 35;     // OK
person[1] = "35";   // エラー: number型でなければなりません

Tuple型の実用例

関数の戻り値としての使用

Tupleは関数の戻り値として複数の値を返す際に便利です。

function getCoordinates(): [number, number] {
  return [10, 20];
}

let coordinates = getCoordinates();
console.log(coordinates[0]); // 10
console.log(coordinates[1]); // 20

フォームデータの処理

例えば、フォームから入力されたデータを処理する場合に、Tupleを使って複数の値を返すことができます。

type FormData = [string, number, boolean];

function processFormData(name: string, age: number, isMember: boolean): FormData {
  return [name, age, isMember];
}

let formData = processFormData("John", 25, true);
console.log(formData); // ["John", 25, true]

オプショナル要素

Tupleの一部の要素をオプショナル(省略可能)にすることができます。

let optionalTuple: [number, string?];
optionalTuple = [42];       // OK
optionalTuple = [42, "Hi"]; // OK

可変長Tuple

Tupleの最後に可変長引数(レスト要素)を追加できます。

let restTuple: [number, ...string[]];
restTuple = [42];                   // OK
restTuple = [42, "Hello", "World"]; // OK

Tuple型の実用的な使用方法

APIレスポンスの処理

APIからのレスポンスで複数の値を受け取る場合にTupleを使用すると便利です。

type ApiResponse = [number, string, boolean];

function fetchUserData(): ApiResponse {
  // APIからのデータ取得をシミュレーション
  let statusCode = 200;
  let message = "Success";
  let data = true;
  
  return [statusCode, message, data];
}

let response = fetchUserData();
let [status, msg, isSuccess] = response;
console.log(status);  // 200
console.log(msg);     // "Success"
console.log(isSuccess); // true

イベントハンドラ

イベントハンドラでイベントオブジェクトと追加データをまとめて扱う場合にTupleを使用できます。

type EventData = [Event, string];

function handleClick(event: Event, message: string): EventData {
  console.log(event.type); // "click"
  console.log(message);    // "Button clicked!"
  return [event, message];
}

let button = document.querySelector("button");
button?.addEventListener("click", (event) => {
  handleClick(event, "Button clicked!");
});

Tuple型と混同しやすい型

配列型(Array)

配列型は、同じ型の要素を任意の数だけ持つことができます。

let numbers: number[] = [1, 2, 3, 4, 5];

オブジェクト型(Object)

オブジェクト型は、プロパティ名とその値のペアの集合です。

let person = {
  name: "Alice",
  age: 30
};

まとめ

Tuple型は、特定の順序と型を持つ配列で、関数の戻り値や複数の異なる型のデータをまとめて扱うのに便利です。配列やオブジェクトとは異なる点を理解し、適切に使い分けましょう。

ポイント:

  • 順序と型が決まっているため、Tupleを使うとコードの安全性と可読性が向上します。
  • 関数の戻り値として複数の値を返す際に便利です。
  • APIレスポンスの処理イベントハンドラでの利用も効果的です。

Tuple型を活用して、TypeScriptでの開発をさらに効率的にしましょう!

参考文献
「現場で使えるTypeScript詳解実践ガイド」

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?