const与readonly详解
今天,我们将深入探讨在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关键字,我们能更灵活地使用它们来保障代码的可维护性和可读性。