I want to use const
keyword in my program.
export class Constant {
let result : string;
private const CONSTANT = 'constant'; //Error: A class member cannot have the const keyword.
constructor () {}
public doSomething () {
if (condition is true) {
//do the needful
}
else
{
this.result = this.CONSTANT; // NO ERROR
}
}
}
Question1: why the class member does not have the const keyword in typescript?
Question2: When I use
static readonly CONSTANT = 'constant';
and assign it in
this.result = this.CONSTANT;
it displays error. why so?
I have followed this post How to implement class constants in typescript? but don't get the answer why typescript is displaying this kind of error with const
keyword.
Creating Read-Only Properties in TypeScript To create a read-only property, we prefix the keyword readonly before the property name. In the example below the price property is marked as readonly . We can assign a value to the price property when we initialize the object. However, we cannot change its value afterward.
Summary: they are the same but const is for variables & readonly is for class properties.
Use the readonly modifier to declare constants in a class. When a class field is prefixed with the readonly modifier, you can only assign a value to the property inside of the class's constructor. Assignment to the property outside of the constructor causes an error.
TypeScript includes the readonly keyword that makes a property as read-only in the class, type or interface. Prefix readonly is used to make a property as read-only. Read-only members can be accessed outside the class, but their value cannot be changed.
Question1: why the class member does not have the const keyword in typescript?
By design. Among other reasons, because EcmaScript6 doesn't either.
This question is specifically answered here : 'const' keyword in TypeScript
Question2: When I use
static readonly CONSTANT = 'constant';
and assign it in
this.result = this.CONSTANT;
it displays error. why so?
If you use static
, then you can't refer to your variable with this
, but with the the name of the class !
export class Constant{
let result : string;
static readonly CONSTANT = 'constant';
constructor(){}
public doSomething(){
if( condition is true){
//do the needful
}
else
{
this.result = Constant.CONSTANT;
}
}
}
Why ? Because this
refers to the instance of the class to which the field / method belongs. For a static variable / method, it doesn't belong to any instance, but to the class itself (quickly simplified)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With