typescript タプルを使用する
- 作成日 2020.12.23
- 更新日 2022.02.27
- 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
-
前の記事
Ruby 配列同士を結合させる 2020.12.22
-
次の記事
python numpyで等差数列の配列を作成する 2020.12.23
コメントを書く