15
10

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 5 years have passed since last update.

TypeScript: 読み取り専用の配列型を宣言する3つの方法

Posted at

本稿では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]
15
10
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
15
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?