网站飘窗 两学一做,网站注册账号怎么做,国外汽车配件网站模板,电商品牌推广方案const与readonly详解
大家好#xff0c;我是免费搭建查券返利机器人赚佣金就用微赚淘客系统3.0的小编#xff0c;也是冬天不穿秋裤#xff0c;天冷也要风度的程序猿#xff01;今天#xff0c;我们将深入探讨在TypeScript中常用的const与readonly关键字#xff0c;了解它…const与readonly详解
大家好我是免费搭建查券返利机器人赚佣金就用微赚淘客系统3.0的小编也是冬天不穿秋裤天冷也要风度的程序猿今天我们将深入探讨在TypeScript中常用的const与readonly关键字了解它们的作用、使用场景以及区别。
什么是const与readonly
在TypeScript中const和readonly都是用于声明常量或只读变量的关键字但它们在使用场景和行为上有一些不同之处。
const关键字
const用于声明常量一旦赋值后就不能再修改。示例代码如下
const PI 3.14;
// PI 3.14159; // Error: Cannot assign to PI because it is a constant.readonly关键字
readonly用于声明只读属性可以在声明时或构造函数中初始化但之后就不能再修改。示例代码如下
class Circle {readonly radius: number;constructor(radius: number) {this.radius radius;}// radius cannot be modified in other methods
}区别与使用场景 const适用于基本数据类型和对象引用 const适用于声明基本数据类型和引用类型的常量但对于引用类型只是保证引用地址不变而非对象的内部属性不变。 const name: string John;
const person: { age: number } { age: 25 };// For objects, properties can still be modified
person.age 26;readonly适用于类属性和数组 readonly更适用于类的属性和数组用于确保对象属性或数组元素的不可修改性。 class Car {readonly brand: string;constructor(brand: string) {this.brand brand;}
}const myCar new Car(Toyota);
// myCar.brand Honda; // Error: Cannot assign to brand because it is a read-only property.const numbers: readonly number[] [1, 2, 3];
// numbers.push(4); // Error: Property push does not exist on type readonly number[].const是编译时常量readonly是运行时常量 const是在编译时计算并内联的常量而readonly是在运行时进行检查的。 const dynamicValue Math.random(); // computed at runtime
const CONST_VALUE dynamicValue; // Error: Initializer of CONST_VALUE is not a constant expression.注意事项 const的注意事项 对于复杂对象const只能保证其引用地址不变内部属性可变。 readonly的注意事项 readonly适用于类的实例属性和数组但在一些情况下可能需要使用const辅助。
结语
通过深入了解const与readonly关键字我们能更灵活地使用它们来保障代码的可维护性和可读性。