はじめに
TypeScriptで配列とタプルを扱い方を簡単にまとめました。
配列の要素として持つ値の型を定義できる
// シンプルな配列の型定義
const colors: string[] = ['red', 'blue']
colors.push('yellow') // OK
// colors.push(123) // コンパイルエラー
console.log('sample:', colors)
配列定義方法:T[]とArrayは同義
const even: Array<number> = [2, 4, 6]
even.push(8) // OK
// even.push("100") // コンパイルエラー
console.log('sample:', even)
合併型も使える
特別な理由がない限り使わないほうがよい
for文等で値を取得する際に値の型に気をつけないといけないから
// 合併型を用いた配列の型定義
const ids: (string | number)[] = ['ABC', 123]
ids.push('DEF') // OK
ids.push(456) // OK
console.log('sample:', ids)
配列の型推論
アノテーションしなくても型推論される
// 型推論された配列の生成
const generateSomeArray = () => {
const _someArray = [] // any[] * 変数名の_は、内部だけで扱われるという意味
_someArray.push(123) // number[]として推論される
_someArray.push('ABC') // (string | number)[]として推論される
return _someArray
}
const someArray = generateSomeArray()
someArray.push(444)
// someArray.push(true) // generateSomeArray()は(string | number)[]の配列を返すと推論されるので、booleanは追加されない
console.log('sample:', someArray)
タプルについて〜より厳格な配列〜
タプルは配列の各要素の数と型を定義できる
// 一般的なタプルの型定義
const response: [number, string] = [200, 'OK']
// response = [400, "Bad Request", "Email parameter is missing"] // 定義された要素数と合わない
// response = ["400", "Bad Request"] // numberにstringを代入できない
console.log('sample:', response)
可変長(レストパラメーター)も使える
// 可変長引数を使ったタプル
const restParameters: [string, ...string[]] = ['ABC', 'DEF', 'GHI']
restParameters.push('JKL')
console.log('sample:', restParameters)
イミュータブルな配列
Javascriptの配列はconstで宣言してもミュータブル(書き換え可)
// Javascriptの配列
const commands1: string[] = ['git add', 'git commit', 'git push']
commands1.push("git fetch") // 追加OK
commands1[2] = "git pull" // 代入OK
console.log('sample:', commands1)
readonlyでイミュータブル(書き換え不可)な配列/タプルを作れる
// 読み取り専用の配列
const commands2: readonly string[] = ['git add', 'git commit', 'git push']
// commands2.push("git fetch") // 追加不可
// commands2[2] = "git pull" // 代入不可
console.log('sample:', commands2)
readonlyの別の書き方
// 読み取り専用の定義方法
const immutableNumbers: ReadonlyArray<number> = [1, 2, 3]
// immutableNumbers.push(4) // NG
console.log('sample:', immutableNumbers)
const immutableNames: Readonly<string[]> = ['Tarou', 'Kazu', 'Yuto']
// immutableNames.push("Takashi") // NG
console.log('sample:', immutableNames)
↧