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】array型とtuple型の違いを表解で解説する

Posted at

はじめに

array型とtuple型ともに、配列で表示されることから具体的に何が違うかわからなくなった方もいるのはないでしょうか?自分もその一人でした。そこで本記事では、一見似ているarray型とtuple型の違いについて、備忘録としてまとめておきます。

array型とtuple型の違い

特徴

array型とtuple型の違いは主に下記のようになります。

型の種類 記法 特徴
array型 (型)[] 初期定義の配列の型制限が緩い
tuple型 [(型1), (型2),...] 初期定義の配列の型制限が厳しい

次に、型制限の「緩い」「厳しい」について具体的に見ていきます。

型制限が緩い/厳しいとは...?

array型は初期段階で配列を定義する型制限が緩く、tuple型は型制限が厳しくなっています。
具体的なソースコードは下記の通りです。

// array型の配列定義(配列の要素数はいくつでもOK)
const fruits: string[] = ["apple", "banana", "strawberry"];

// tuple型の配列定義(配列の要素数は宣言した型とその数のみ定義可能)
const fruitsInfo: [string, number, boolean] = ["apple", 1500, true];

このように、最初に定義した配列について、

  • array型(型制限が緩い):配列の要素数は宣言した型であれば、いくつでも宣言してOK

  • tuple型(型制限が厳しい):配列の要素数は宣言した型と、その個数が対応する必要あり

といった違いがあります。ちなみにいずれの型も追加/配列/削除を行うことが可能です。

add.ts
// 追加(array型)
const fruits: string[] = ["apple", "banana", "strawberry"];
fruits.push("grape"); // ["apple", "banana", "strawberry", "grape"]
fruits.push(1000); // 型が異なるのでエラー

// 追加(tuple型)
const fruitsInfo: [string, number, boolean] = ["apple", 1500, true];
fruitsInfo.push("banana"); // ["apple", 1500, true, "banana"]
update.ts
// 追加(array型)
const fruits: string[] = ["apple", "banana", "strawberry"];
fruits[1] = "grape"; // ["apple", "grape", "strawberry"]
fruits[1] = 1000; // 型が異なるのでエラー

// 追加(tuple型)
const fruitsInfo: [string, number, boolean] = ["apple", 1500, true];
fruitsInfo[1] = 1000; // ["apple", 1000, true]
fruitsInfo[1] = true; // 型が異なるのでエラー
delete.ts
// 追加(array型)
const fruits: string[] = ["apple", "banana", "strawberry"];
fruits.pop(); // ["apple", "banana"]

// 追加(tuple型)
const fruitsInfo: [string, number, boolean] = ["apple", 1500, true];
fruitsInfo.pop(); // ["apple", 1500]

まとめ

今回は、array型とtuple型の違いを解説しました。
最初の配列宣言における型制限の厳しさに違いがあり、配列の追加/更新/削除などはどちらの型も同じように行えることがわかりました。

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?