📅  最后修改于: 2023-12-03 14:47:02.281000             🧑  作者: Mango
In TypeScript, readonly
and const
are used to ensure that values are not modified. Both keywords appear to be similar, but they have a few key differences.
const
is used to declare a variable whose value is not allowed to change. The value must be assigned when the variable is declared, and cannot be reassigned thereafter.
For example:
const PI = 3.14159;
PI = 3.14; // Compile error!
readonly
is used to declare a property or a class member whose value cannot be modified once it is set. Unlike const
, readonly
can be declared without an initial value. The value can be set in the constructor of the class.
For example:
class Person {
readonly name: string;
readonly age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let p1 = new Person("John Doe", 23);
p1.name = "Jane Doe"; // Compile error!
const
is used for variables, while readonly
is used for properties and class members.
const
values must be assigned when declared, whereas readonly
values can be set in the constructor.
const
values cannot be reassigned, while readonly
values cannot be modified once they are set.
In conclusion, const
and readonly
serve different purposes in TypeScript. const
is used to declare variables whose values cannot be changed, while readonly
is used to declare class members or properties that should not be modified once they are set.