const与readonly详解

const与readonly详解

大家好,我是免费搭建查券返利机器人赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天,我们将深入探讨在TypeScript中常用的constreadonly关键字,了解它们的作用、使用场景以及区别。

什么是const与readonly?

在TypeScript中,constreadonly都是用于声明常量或只读变量的关键字,但它们在使用场景和行为上有一些不同之处。

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
}

区别与使用场景

  1. const适用于基本数据类型和对象引用: const适用于声明基本数据类型和引用类型的常量,但对于引用类型,只是保证引用地址不变,而非对象的内部属性不变。

    const name: string = "John";
    const person: { age: number } = { age: 25 };
    
    // For objects, properties can still be modified
    person.age = 26;
    
  2. 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[]'.
    
  3. 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.
    

注意事项

  1. const的注意事项: 对于复杂对象,const只能保证其引用地址不变,内部属性可变。

  2. readonly的注意事项: readonly适用于类的实例属性和数组,但在一些情况下可能需要使用const辅助。

结语

通过深入了解constreadonly关键字,我们能更灵活地使用它们来保障代码的可维护性和可读性。

  • 20
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值