1
2

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 1 year has passed since last update.

【TypeScript】タプルについて

Last updated at Posted at 2022-07-17

配列の型付けをする時にタプルを使える時は積極的に使う

タプル(tuple) は配列のサブタイプ。
固定長の配列を型付けするための特別な方法。
不均一なリストを安全にコード化するだけでなく、それが型付けするリストの長さを限定する。

シンプルな使い方

let a: [number]  = [1];

// [苗字, 名前,  生まれ年]のタプル
let b: [string, string, number] = ['鈴木', '太郎', 1989];

b = ['佐藤', '一郎', '愛知県', 1963];  // 愛知県は型付けされていないためエラー

?(オプション)を使った省略

let a: [number, number?][] = [
  [1],
  [3, 4],
  [5]
];

最小限の長さをもった制約をつける

// 少なくとも1つの要素(ともにそれに続く可変長さの要素)をもつ文字列のリスト
let a: = [string, ...string[]] = ['太郎', '二郎', '三郎'];  

// 不均一なリスト
let b: = [number, boolean, ...string[]] = [1, false, 'a', 'b', 'c'];
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?