DEV Community

Noah
Noah

Posted on

1

Cautions When Using readonly in TypeScript

The basic of readonly property

In Type Script, you can make the object of the properties of an object read-only.

const person: { readonly name: string  } = { name: 'Mike' }

person.name = 21;
// → Cannot assign to 'name' because it is a read-only property.
Enter fullscreen mode Exit fullscreen mode

⚠️① readonly is only at compile-time

In the compiled JavaScript code, the readonly declaration is removed, so it will not be detected as an error at runtime.

⚠️② readonly is not recursive.

const person: {
  readonly name: string;
  readonly academicBackground: {
    primarySchool: string
  }
} = {
  name: 'Mike',
  academicBackground: {
    primarySchool: 'School A'
  }
}

person.academicBackground.primarySchool = 'School B'
// You can change `person.academicBackground.primarySchool`
Enter fullscreen mode Exit fullscreen mode

If you want to make it read-only, also you need to put readonly to primarySchool.

const person: {
  readonly name: string;
  readonly academicBackground: {
    readonly primarySchool: string
  }
} = {
  name: 'Mike',
  academicBackground: {
    primarySchool: 'School A'
  }
}

person.academicBackground.primarySchool = 'School B'
// → Cannot assign to 'primarySchool' because it is a read-only property.
Enter fullscreen mode Exit fullscreen mode

Readonly

When the number of properties increases, adding readonly to each one becomes cumbersome and increases the amount of code.
You can refactor by using Readonly.

const obj: {
  readonly a : string;
  readonly b: string;
  readonly c: string;
  readonly d: string;
} = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
}

// ↓

const obj: Readonly<{
  a : string;
  b: string;
  c: string;
  d: string;
}> = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
}
Enter fullscreen mode Exit fullscreen mode

Happy Coding☀️

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay