本稿ではTypeScriptで変更不可(immutable)な読み取り専用の配列型を宣言する方法を紹介する。
readonly T[]
const numbers: readonly number[] = [1, 2, 3]
numbers.push(4) // 🚫コンパイルエラー: Property 'push' does not exist on type 'readonly number[]'.
numbers.pop() // 🚫コンパイルエラー: Property 'pop' does not exist on type 'readonly number[]'.
as
で型表明(type assertion)をするのと同じ。
const numbers = [1, 2, 3] as readonly number[]
ReadonlyArray<T>
readonly T[]
と全く同じ。別の書き方と考えてよい。
const numbers: ReadonlyArray<number> = [1, 2, 3]
numbers.push(4) // 🚫コンパイルエラー
numbers.pop() // 🚫コンパイルエラー
numbers
の型はreadonly number[]
になる。
as
で型表明(type assertion)をするのと同じ。
const numbers = [1, 2, 3] as ReadonlyArray<number>
as const
const numbers = [1, 2, 3] as const
numbers.push(4) // 🚫コンパイルエラー: Property 'push' does not exist on type 'readonly [1, 2, 3]'.
numbers.pop() // 🚫コンパイルエラー: Property 'pop' does not exist on type 'readonly [1, 2, 3]'.
readonly T[]
と異なり、numbers
の型はreadonly [1, 2, 3]
になる。
これと同じ型になるような型アノテーションの書き方は次のとおり:
const numbers: readonly [1, 2, 3] = [1, 2, 3]