Difference between const and readonly in typescript

后端 未结 5 887
醉酒成梦
醉酒成梦 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:42

    One of the key difference between const and readonly is in how it works with the array. (appart form already ans diff) You have to use ReadonlyArray while working with Array, where T is generic type(google it for more).

    when u declare any array as const, you can perform operations on array which may change the array elements. for ex.

    const Arr = [1,2,3];
    
    Arr[0] = 10;   //OK
    Arr.push(12); // OK
    Arr.pop(); //Ok
    
    //But
    Arr = [4,5,6] // ERROR
    

    But in case of ReadonlyArray you can not change the array as shown above.

    arr1 : ReadonlyArray = [10,11,12];
    
    arr1.pop();    //ERROR
    arr1.push(15); //ERROR
    arr1[0] = 1;   //ERROR
    

提交回复
热议问题