typescript タプルを使用する

typescript タプルを使用する

typescriptで、タプルを使用するサンプルコード記述してます。タプル型は[string, number]の形で表します。typescriptのバージョンはVersion 4.1.2となります。

環境

  • OS windows10 64bit
  • typescript Version 4.1.2

タプルを使用

typescriptでは、型を定義してタプルを使用することが可能です。

let tpl: [string, number, number]

tpl = ['mebee', 1, 10];

for (const i of tpl) {
    console.log(i);
  }
// mebee
// 1
// 10

定義した型と違う型を使用するとエラーになります。

tpl = ['mebee', 1, 'hello'];
//error TS2322: Type 'string' is not assignable to type 'number'.

for ofで表示してますが、forEachを使用することも可能です。

arr.forEach(i => console.log(i));

また、タプルを使用すると、関数の戻りに複数の値を利用することが可能になります。

function err(): [number, string] {
    return [1, 'error'];
}

const [errcode, errmessage] = err();

console.log(errcode);
// 1

console.log(errmessage);
  // error