TypeScriptUtility types

Readonly<Type>

Creates a type where every property is read-only.

On this page

Example

#
TypeScript
interface State {
  level: number
  exp: number
}

function levelUp(state: Readonly<State>): State {
  return { level: state.level + 1, exp: 0 }
}

const current: Readonly<State> = { level: 4, exp: 980 }
console.log(levelUp(current))
console.log(current)
Result
{ level: 5, exp: 0 }
{ level: 4, exp: 980 }

Definition and usage

#

Readonly<Type> adds the readonly modifier to every field. You can read an object of that type, but any attempt to assign a new value to a field ends in a compile error.

It’s a convenient way to signal that a function doesn’t change the object it receives, or to protect application state from an accidental mutation.

The protection only works at compile time, and only shallowly. Nested objects can still be modified, and at runtime you can change the object without any trouble, unless you use Object.freeze().

Syntax

#
Syntax
type New = Readonly<Type>

Type parameters

#
  • Type

    object type

    The type whose fields should be read-only.

More examples

#
An attempted mutation
TypeScript
current.exp = 1000
// Error: Cannot assign to 'exp' because it is a read-only property.

Good practices

#
  • Mark parameters as Readonly<T> when the function shouldn’t change them. The compiler will catch accidental mutations.
  • For arrays, use readonly T[] or ReadonlyArray<T>.

Related entries

#

Spotted a mistake or missing an example? Write to us.