20
9

More than 1 year has passed since last update.

【TypeScript】as const(const アサーション) を理解する

Last updated at Posted at 2021-09-03

as const(const アサーション) とは

  • 全ての値をreadonly(読み取り専用、変更不可)にするアサーション。
  • ネストしたオブジェクトに対してもreadonly(読み取り専用、変更不可)にしてくれる
  • widening も抑止してくれる

● アサーションの参考資料

as const を使ってみる

オブジェクトで

値を変更しようとすると、
Cannot assign to 'first' because it is a read-only property.
firstは読み取り専用だから、適用できないよ」と怒られる。

const sampleObj = {
  first: '最初',
  second: '2番目',
  third: '3番目',
  fourth: '4番目',
} as const

sampleObj.first = 'さいしょ' // Cannot assign to 'first' because it is a read-only property.

as constをコメントアウトすれば怒られない。

const sampleObj = {
  first: '最初',
  second: '2番目',
  third: '3番目',
  fourth: '4番目',
} // as const

sampleObj.first = 'さいしょ'

配列で

配列でも同様。

値を変更しようとすると、
Cannot assign to '3' because it is a read-only property.
3は読み取り専用だから、適用できないよ」と怒られる。

const sampleArr = ['最初', '2番目', '3番目', '4番目'] as const

sampleArr[3] = 'フォース' //  Cannot assign to '3' because it is a read-only property.

as constをコメントアウトすれば怒られない。

const sampleArr = ['最初', '2番目', '3番目', '4番目'] // as const

sampleArr[3] = 'フォース'

最後に

ありがとうございました!!

20
9
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
20
9