Typescript Tutorials - How to implement constants property in a class


Class properties constants in typescript.

Constants are fixed values, can not be modified once assigned with value, These can be declared in class like a member variables in any programming languages like java.

but typescript does not allow class level constants. What will happen if class declares constants member variables.

class Employee {
    const defaultValue = 10;

    calculate() {
        console.log(this.defaultValue);
    }
}

In The above class, with line constant declaration throws compile error A class member cannot have the ‘const’ .

In typescript,There are many ways we can achieve declaring member constants in typescript class declarations.

  • readonly keyword
  • static with readonly properties

readonly property constants.

keyword readonly is added to typescript language with 2.0 version.

Important points

  • readonly properties are not modified once value is assigned.
  • one way is to declare and assign with value in readonly properties
  • other ways is readonly properties can be declared at class level and assign with value in constructor only.
  • assigning readonly properties outside construtor are not allowed

The same class can be rewritten with readonly property keyword

readonly properties are assigned with value when property is declared as follows

class Employee {

    readonly defaultValue = 10;

    calculate() {
        console.log(this.defaultValue);
        this.defaultValue=40 // gives compilation error
        console.log(this.defaultValue);
    }
}

readonly properties makes properties are initilized and act as constants. if you try to assign new value, ie this.defaultValue=40, It throws error Cannot assign to ‘defaultValue’ because it is a read-only property

readonly property can be declared, but not assigned, initilize the value in constructor as follows

class Employee {
    readonly defaultValue:number ;
    constructor(value: number){
      this.defaultValue=value;
    }
    calculate() {
        console.log(this.defaultValue);

    }
}
let emp=new Employee(123)
emp.calculate();

static readonly property constants.

static allows to declare and assign value at class level only. assign values in constructor and other places are not allowed.

class Employee {
    static readonly defaultValue:number ;
    constructor(value: number){
      Employee.defaultValue=value; // gives compilation error
    }
    calculate() {
        console.log(Employee.defaultValue);

    }
}

let emp=new Employee(123)
emp.calculate();

Static with readonly property are act as like real constants.

Similar Posts