Complete Typescript Class constants tutorials

Typescript Static are readonly constants: Learn how to declare constants in typescript classes and constructors with rules.

You can also check Typescript final keyword

Class properties constants in typescript

Constants are fixed values that cannot be changed once assigned a value. In any programming language, such as Java, these are declared in class-like member variables.

But typescript does not allow class-level constants.

What will happen if the class declares constants member variables?

class Employee {
  defaultValue = 10;

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

The line constant declaration in the above class throws a compile error A class member cannot have the ‘const’. Declaring member constants in typescript class declarations can be done in many ways.

  • readonly keyword
  • static with readonly properties

Typescript readonly property constants

Keyword readonly is added to typescript language with the 2.0 version.

Important points

  • readonly properties are not modified once the value is assigned.
  • One way is to declare and assign with value in readonly properties
  • another way is readonly properties can be declared at class level and assigned with value in constructor only.
  • Assigning readonly properties outside the constructor is not allowed

The same class can be rewritten with the readonly property keyword

readonly properties are assigned with value when the 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 make properties initialized and act as constants.

if you try to assign a new value, ie this.defaultValue=40, It throws the error Cannot assign to ‘defaultValue’ because it is a read-only property

The readonly property can be declared, but not assigned, initialize the value in the 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

The keyword static allows you to declare and assign values only at the class level. It is not allowed to assign values in the constructor or anywhere else.

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 declaration is equal to real constants.

Conclusion

To Sum up, You learned how to declare class-level constants in a typescript class.