Difference between const and readonly in typescript

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

    I think the reason for both words is probably that it's easier to implement than the alternative.

    In C++, for instance, classes can have const members. But C++ has special syntax to initialize the constants before the constructor is run, so there's never really any "assignment" to the const going on, like:

    class TestClass {
        const int _x;
        TestClass(int x) : _x(x) {}
    }
    

    The _x(x) initializes the _x variable before the constructor is called.

    In Typescript, if they wanted to allow members to be declared const and were serious about the variables being const, they would need to add similar syntax.

    "readonly" isn't really the same as const. It means, I think, something slightly different. It means "allow assignment inside the constructor, but then no more."

提交回复
热议问题