TypeScript readonly: Immutable Types
The TypeScript readonly modifier is a promise you make to the compiler: this property gets assigned once, and nothing reassigns it afterwards. Put it on a property and every later write becomes a compile error. That is the entire feature, and it is also the source of every misunderstanding about it, because the promise is checked at compile time and then thrown away.
This page covers where readonly goes, how it behaves on arrays and tuples, what Readonly<T>
adds on top, and the two limits that catch people out: it is shallow, and it does not exist at
runtime.
It is worth being clear about what you are buying up front. readonly is a documentation tool
that the compiler enforces. It tells the next person reading your code — often you, months later
— which fields are part of an object's identity and which are free to change. The compiler then
holds you to it. What it is not is a security boundary or a runtime guarantee, and treating it
like one is how people end up surprised.
What TypeScript readonly actually does
readonly is a property modifier. It sits in front of a property name in an interface, a type
alias, or a class body, and it blocks assignment to that property after initialisation.
interface AccountSettings {
readonly id: string
theme: 'light' | 'dark'
}
const accountSettings: AccountSettings = { id: 'acc_1', theme: 'dark' }
accountSettings.theme = 'light' // ✅ theme is a normal property
// accountSettings.id = 'acc_2'
// ❌ Cannot assign to 'id' because it is a read-only property. ts(2540)Reading is always fine. Only writing is blocked, and only through a type that still says
readonly. That second half matters more than it sounds, because the modifier is erased the
moment TypeScript compiles your file.
const escapeHatch = accountSettings as { id: string }
escapeHatch.id = 'acc_mutated'
console.log(accountSettings.id) // 'acc_mutated'No error, and the object really did change. readonly is a type-level annotation, not a runtime
lock. If you need the object to genuinely refuse writes in production, you need Object.freeze,
which we come back to further down.
readonly on interfaces, type aliases and classes
The modifier works the same way in all three places.
type CoordinatePoint = {
readonly x: number
readonly y: number
}
const originPoint: CoordinatePoint = { x: 0, y: 0 }
console.log(originPoint.x + originPoint.y)Classes get one extra rule, and it is the useful one: a readonly field can still be assigned
inside the constructor. That is what makes it the right modifier for identity fields.
class InvoiceRecord {
readonly invoiceId: string
amountDue: number
constructor(invoiceId: string, amountDue: number) {
this.invoiceId = invoiceId // ✅ the constructor is allowed to write
this.amountDue = amountDue
}
applyDiscount(percent: number) {
this.amountDue = this.amountDue * (1 - percent)
// this.invoiceId = 'inv_2'
// ❌ Cannot assign to 'invoiceId' because it is a read-only property. ts(2540)
}
}
const marchInvoice = new InvoiceRecord('inv_1', 400)
marchInvoice.applyDiscount(0.1)You can shorten that with a parameter property, which declares and assigns the field in one go. Our guide to TypeScript classes covers the rest of the modifiers that can ride along with it.
class AuditEntry {
constructor(
readonly entryId: string,
public message: string,
) {}
}
const firstEntry = new AuditEntry('log_1', 'created')
console.log(firstEntry.entryId)Interfaces are where you will reach for readonly most often, because an
interface describes a shape you hand to other people's code, and the modifier documents which
parts of that shape they are allowed to touch.
readonly arrays and ReadonlyArray
Arrays get their own spelling. Put readonly in front of the array type and the mutating methods
disappear from it entirely.
const weekdayNames: readonly string[] = ['mon', 'tue', 'wed']
const firstWeekday = weekdayNames[0] // ✅ indexing still works
console.log(firstWeekday, weekdayNames.length, weekdayNames.map((day) => day.toUpperCase()))
// weekdayNames.push('thu')
// ❌ Property 'push' does not exist on type 'readonly string[]'. ts(2339)push, pop, splice, sort and reverse are gone. The methods that return a new array —
map, filter, slice, concat — are all still there, which is exactly the split you want.
This is a stronger guarantee than the property modifier gives you, and it is the one place where
readonly does real work in day-to-day code. A readonly array type genuinely removes the
mutating half of the API surface rather than just blocking reassignment, so the compiler catches
the mistake at the call site instead of three functions later when something re-sorted an array
that the caller still had a reference to.
There is a longhand spelling too, and the two are identical:
const longFormWeekdays: ReadonlyArray<string> = weekdayNames
const shortFormWeekdays: readonly string[] = longFormWeekdays
console.log(shortFormWeekdays.join(', '))Note that readonly string[] is the only shorthand that works. readonly Array<string> is a
syntax error, and the modifier also cannot be applied to a type alias that happens to resolve to
an array. The TypeScript array types page goes deeper into the
inference rules around all of this.
Tuples take the same modifier, and it behaves the same way:
const rgbOrange: readonly [number, number, number] = [255, 128, 0]
console.log(rgbOrange[0])Readonly<T>, the utility type
Marking every property by hand gets old. Readonly<T> does it for you in one pass.
type UserProfile = {
name: string
email: string
}
type FrozenUserProfile = Readonly<UserProfile>
// { readonly name: string; readonly email: string }
declare const frozenProfile: FrozenUserProfile
console.log(frozenProfile.email)
// frozenProfile.name = 'ada'
// ❌ Cannot assign to 'name' because it is a read-only property. ts(2540)It is not magic. Readonly<T> is a mapped type in the standard library,
and it is short enough to write yourself:
type MyReadonly<T> = {
readonly [K in keyof T]: T[K]
}
type FrozenPoint = MyReadonly<CoordinatePoint>
declare const frozenOrigin: FrozenPoint
console.log(frozenOrigin.x)That is the whole implementation, and writing it is the Readonly challenge
on this site. Readonly<T> sits in the same family as Partial, Required and Pick — the
utility types page walks through the full set.
readonly is one level deep
Here is the limit that surprises everyone. readonly protects the property, not whatever the
property points at.
type TeamConfig = {
readonly name: string
readonly members: string[]
}
const coreTeam: TeamConfig = { name: 'core', members: ['ada'] }
// coreTeam.name = 'platform'
// ❌ Cannot assign to 'name' because it is a read-only property. ts(2540)
coreTeam.members.push('grace') // ✅ no error at allThe members property cannot be replaced, but the array it holds is a perfectly ordinary
mutable array. If you want the whole structure locked, say so — either by writing
readonly members: readonly string[], or by recursing with a mapped type:
type DeepFrozen<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepFrozen<T[K]> : T[K]
}
type FrozenTeamConfig = DeepFrozen<TeamConfig>
declare const frozenTeam: FrozenTeamConfig
console.log(frozenTeam.members.length)
// frozenTeam.members.push('grace')
// ❌ Property 'push' does not exist on type 'readonly string[]'.That version is deliberately simplified — functions, Date, Map and Set all satisfy
extends object and get mapped over too, which is rarely what you want. Getting it right is the
Deep Readonly challenge, and it is a good one.
readonly vs const vs Object.freeze
Three things that sound like they do the same job, and all three do something different.
const protects the binding. You cannot point the name at a different value, but the value
itself is fair game:
const retryPolicy = { retries: 3 }
retryPolicy.retries = 5 // ✅ const says nothing about the contents
// retryPolicy = { retries: 5 }
// ❌ Cannot assign to 'retryPolicy' because it is a constant. ts(2588)readonly protects the property, at compile time only, as we saw above.
Object.freeze protects the object at runtime. TypeScript types its return as Readonly<T>,
so you get the compile error as well:
const serviceLimits = Object.freeze({ maxUsers: 10 })
console.log(serviceLimits.maxUsers)
// serviceLimits.maxUsers = 20
// ❌ Cannot assign to 'maxUsers' because it is a read-only property. ts(2540)The practical rule: use readonly for intent inside your own codebase, and Object.freeze only
when untyped code might reach the object and you need a real guarantee.
Which direction is assignable
readonly is not part of the structural comparison for properties, which is why the next snippet
looks lopsided. For arrays it is enforced, and the direction only goes one way.
function countItems(items: readonly string[]): number {
return items.length
}
const mutableTags: string[] = ['a', 'b']
const readonlyTags: readonly string[] = ['c', 'd']
countItems(mutableTags) // ✅ a mutable array satisfies a readonly parameter
countItems(readonlyTags) // ✅
function appendItem(items: string[]): void {
items.push('new')
}
appendItem(mutableTags) // ✅
// appendItem(readonlyTags)
// ❌ Argument of type 'readonly string[]' is not assignable to parameter of type 'string[]'. ts(2345)The takeaway is worth internalising: annotate array parameters as readonly whenever your
function does not mutate them. It costs nothing, every caller still works, and it stops a future
version of your function from quietly mutating an argument.
as const for deeply readonly literals
as const is the shortcut when the value is a literal you write out in full. It makes every
property readonly, all the way down, and narrows the values to their literal types at the same
time.
const routeConfig = {
path: '/users',
methods: ['GET', 'POST'],
} as const
// { readonly path: '/users'; readonly methods: readonly ['GET', 'POST'] }
type RouteMethod = (typeof routeConfig)['methods'][number] // 'GET' | 'POST'
declare const allowedMethod: RouteMethod
console.log(allowedMethod)
// routeConfig.methods.push('DELETE')
// ❌ Property 'push' does not exist on type 'readonly ["GET", "POST"]'. ts(2339)This is the easiest way to get deep immutability, and it works on nested objects and arrays
without any recursive type gymnastics. The catch is that it only applies to literals — you cannot
as const a value that came back from a function.
Where readonly earns its keep
Three patterns cover almost every real use.
Identity fields on classes and entities. An id, a createdAt, a userId — anything that
defines which record you are holding. Marking them readonly turns a whole category of bug
into a compile error, and it costs one keyword.
Function parameters you do not mutate. This is the highest-value habit on the list. Typing an
array parameter as readonly T[] documents that the function is a pure reader, keeps every
existing caller working, and means a future edit that adds a .sort() fails the build instead of
quietly reordering the caller's data. The same applies to object parameters wrapped in
Readonly<T>.
Configuration and constants. Anything you build once at module load and read everywhere else.
as const usually handles this in one go, and you get literal types for free.
The place readonly is not worth it is local state inside a function body. If a value never
escapes the function, the modifier adds noise without adding information, and you are better off
spending the reader's attention somewhere it matters.
One last thing to know about generics: readonly survives most type transformations but not all
of them. Homomorphic mapped types — ones written as [K in keyof T] — preserve the modifier from
the source type, which is why Partial<Readonly<T>> stays readonly. Hand-rolled mapped types
that build keys some other way usually drop it. If a utility type is mysteriously handing back a
mutable shape, that is the first thing to check.
Wrapping up
readonly marks a property as write-once, and that is checked by the compiler and nowhere else.
Use it on identity fields, on configuration objects, and on every array parameter your functions
do not mutate.
Keep the two limits in mind. It is shallow, so a readonly property holding an array or an object
still hands out a mutable reference — reach for as const on literals, or a recursive mapped type
when you need more. And it vanishes after compilation, so a type assertion or plain JavaScript
walks straight past it.
When you want to practise the type-level side, Readonly builds the utility from scratch, Readonly 2 adds key selection, and Get Readonly Keys asks you to detect the modifier rather than apply it.
Become a TypeScript Pro
Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges