Difference between const and readonly in typescript

后端 未结 5 880
醉酒成梦
醉酒成梦 2021-02-01 11:47

Constant vs readonly in typescript

Declaring a variable as readonly will not allow us to override even if they are public properties.

How const beha

5条回答
  •  迷失自我
    2021-02-01 12:23

    A const variable cannot be re-assigned, just like a readonly property.

    Essentially, when you define a property, you can use readonly to prevent re-assignment. This is actually only a compile-time check.

    When you define a const variable (and target a more recent version of JavaScript to preserve const in the output), the check is also made at runtime.

    So they effectively both do the same thing, but one is for variables and the other is for properties.

    const x = 5;
    
    // Not allowed
    x = 7;
    
    
    class Example {
        public readonly y = 6;
    }
    
    var e = new Example();
    
    // Not allowed
    e.y = 4;
    

    Important note... "cannot be re-assigned" is not the same as immutability.

    const myArr = [1, 2, 3];
    
    // Not allowed
    myArr = [4, 5, 6]
    
    // Perfectly fine
    myArr.push(4);
    
    // Perfectly fine
    myArr[0] = 9;
    

提交回复
热议问题