1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】readonly とas const の違いと使い分け

1
Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。
TypeScript を使っていると、配列やオブジェクトを定義するときに
readonlyas const がよく出てきます。

一見似ているようですが、実は目的と役割が少し違います。
「どちらを使えばいいのか分からない…」と迷うことも多いでしょう。

この記事では readonlyas const の違いを整理し、
さらに 実務での使い分け方まで解説します。


ざっくり結論

  • readonly : 「入れ物(配列やオブジェクト)を変更禁止」にする型注釈。
  • as const : 「値そのものを固定」しつつ、自動で readonly にする値断定。

readonly:変更禁止

type Item = { id: number; name: string };

const arr: readonly Item[] = [
  { id: 1, name: 'math' },
  { id: 2, name: 'english' },
];

arr.push({ id: 3, name: 'japanese' }); // ❌ エラー
arr[0] = { id: 99, name: 'x' }; // ❌ エラー
  • 配列やオブジェクトを破壊的に変更できなくなる
  • ただし 要素の型は広いまま(例: name: string

as const:値を固定

const arr = ['math', 'english'] as const;
// 型: readonly ["math", "english"]

arr[0] = 'japanese'; // ❌ エラー
  • 配列やオブジェクトの値がリテラル型に固定される
  • 自動的に readonly も付与
  • 配列の長さも固定(タプルのような扱い)

違いをまとめると

readonly as const
主な目的 外部からの変更禁止 値を定数化して安全に扱う
型の挙動 広い型のまま リテラル型に縮小
配列の長さ 固定されない 固定される
ユースケース API の返却値を守る 定数リスト・ユニオン型生成

まとめ

  • readonly = 入れ物の変更を禁止
  • as const = 値を固定 + 自動で readonly
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?