Home > Web Front-end > JS Tutorial > body text

Cautions When Using readonly in TypeScript

WBOY
Release: 2024-08-11 06:02:01
Original
330 people have browsed it

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.
Copy after login

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

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.
Copy after login

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'
}
Copy after login

Happy Coding☀️

The above is the detailed content of Cautions When Using readonly in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template