17

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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Aditya
  • 2,358
  • 6
  • 35
  • 61

1 Answers1

29

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)

Umair
  • 6,366
  • 15
  • 42
  • 50
Pac0
  • 21,465
  • 8
  • 65
  • 74