"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Cautions When Using readonly in TypeScript

Cautions When Using readonly in TypeScript

Published on 2024-08-21
Browse:986

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.

⚠️① 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`

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.

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: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
}

Happy Coding☀️

Release Statement This article is reproduced at: https://dev.to/noah-00/cautions-when-using-readonly-in-typescript-22d7?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3