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?

More than 3 years have passed since last update.

TypeScriptのタプル型で定義する要素数を超えるpush時の挙動

Last updated at Posted at 2022-01-27

環境

TypeScript v4.5.5

詳細

TypeScript のタプル型では要素数が固定長の型を定義できる。
しかし、push() メソッドを使うことで定義した要素数を超えて要素を追加できてしまう。

次の例では要素数 2 のタプル t を定義しているが、3 つ目の要素を push できてしまっている。
しかし、さすがに t[2] として定義外の要素を取得することはできない。

const t: [number, boolean] = [1, true];
t.push(3);             // コンパイルエラーにならない!
console.log(t.length); // 3
console.log(t);        // [ 1, true, 3 ]
console.log(t[1]);     // true
console.log(t[2]);     // 長さ '2' のタプル型 '[number, boolean]' にインデックス '2' の要素がありません。ts(2493)

また、定義されていない型、この場合は number と boolean 以外の型を持つ値は push できない。

const t: [number, boolean] = [1, true];
t.push('3'); // 型 '"3"' の引数を型 'number | boolean' のパラメーターに割り当てることはできません。ts(2345)

やや奇妙な挙動に見えなくもないが、型で定義された要素の範囲内(今回の例だとタプルのインデックス 0 から 1)においては、定義通りの型の値を定義通りの順序と要素数を満たした状態でしか代入できないことは保証されている。よって、基本的に本記事で挙げた挙動が問題になることはあまりなさそう。

とはいえこういった挙動があることは頭の片隅に入れておくと良いかも知れない。

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?