Difference between constant and readonly in typescript

Constant vs read-only in typescript

Declaring a variable as readonlywill not allow us to override, even if they are publicly available.

How const works

const SOME_VARIABLE:number = 10;

If I redefine its value, how will it work?

+4
source share
2 answers

A constvariable cannot be re-assigned, like a property readonly.

Essentially, when you define a property, you can use readonlyto prevent reassignment. This is actually just a compile time check.

const ( JavaScript const ), .

, , , - .

const x = 5;

// Not allowed
x = 7;


class Example {
    public readonly y = 6;
}

var e = new Example();

// Not allowed
e.y = 4;

... " " - , .

const myArr = [1, 2, 3];

// Not allowed
myArr = [4, 5, 6]

// Perfectly fine
myArr.push(4);

// Perfectly fine
myArr[0] = 9;
+10

readonly , . ( appart ans diff)   ReadonlyArray Array, T - (google it for more).

u const, , . ,

const Arr = [1,2,3];

Arr[0] = 10;   //OK
Arr.push(12); // OK
Arr.pop(); //Ok

//But
Arr = [4,5,6] // ERROR

ReadonlyArray , .

arr1 : ReadonlyArray<number> = [10,11,12];

arr1.pop();    //ERROR
arr1.push(15); //ERROR
arr1[0] = 1;   //ERROR
0

Source: https://habr.com/ru/post/1686865/


All Articles