How to implement class constants in TypesScript?


In this tutorial, we will learn to implement class constants in TypeScript.

Any application has shared values that need to be used by classes and modules. These numbers could be configuration parameters, environment settings, error codes, or status indications. Using constants to hold those values rather than hard-coding magic strings is recommended. Constant use makes a program manageable by preventing the repetition of values in different places.

Object-oriented JavaScript is TypeScript. Classes, interfaces, and other object-oriented programming are supported by TypeScript. In terms of OOP, a class is a template for building objects. The object's data is contained within a class. Typescript's built-in features aid the class concept. Classes weren't supported in JavaScript ES5 or before. ES6 provides this function to Typescript.

Constants are immutable values that cannot be altered once given a value. These are declared in member variables resembling any programming language's class declarations.

But class-level constants are not supported by Typescript. A class member cannot access the "const". There are numerous ways to declare member constants in typescript class declarations. They are −

  • Using readonly keyword
  • Using static readonly property constants

First, we will learn about how a class is created in Typescript.

Creating a class using its instance

Here we will create a class using its instance of the class. We'll create a class and then use data inside it by making an instance of the class (or object) and calling any specific data.

Syntax

Users can follow the below syntax to create a class in TypeScript −

//Declaring a class
class ClassName {
   // Statement of codes
}

As we can see in the above syntax, here we are creating a class by defining the class name.

Example

In the example below, we can see that we have created a class named “Person”. It has a variable PersonName with the value “TutorialsPoint” of the typed string. Then we made a person object and stored it in the instance variable and console, logging the PersonName variable value.

class Person {
   PersonName: string = "TutorialsPoint"
}
let instance = new Person();
console.log(instance.PersonName);

On compiling, it will generate the following JavaScript code −

var Person = /** @class */ (function () {
   function Person() {
      this.PersonName = "TutorialsPoint";
   }
   return Person;
}());
var instance = new Person();
console.log(instance.PersonName);

Output

The above code will produce the following output −

TutorialsPoint

In the output, users can observe that it shows the value of the PersonName variable, which we called using instance.

Using readonly keyword

This method will create a class using the same syntax as shown earlier. Here, we'll use the readonly keyword, which will assist us in making the value of that particular field non-alterable. Again, the user's browser console will display an error response if we attempt to modify that value.

Example

In the below example, we can see that here we created a class named 'Person'. It has two fields of name and roll with the readonly modifier. That means we cannot update or modify these fields' values outside the constructor. It will display an error. After that, we create a function named displayResult(), showing the values of those fields using the console. And this function is invoked by the instance of the Person class.

class Person{
   readonly name : string = "XYZ";
   readonly roll : number = 20;
   displayResult() : void{
      console.log(this.name);
      console.log(this.roll);
   }
}
  
let instance = new Person();
instance.displayResult();

On compiling, it will generate the following JavaScript code −

var Person = /** @class */ (function () {
   function Person() {
      this.name = "XYZ";
      this.roll = 20;
   }
   Person.prototype.displayResult = function () {
      console.log(this.name);
      console.log(this.roll);
   };
   return Person;
}());
var instance = new Person();
instance.displayResult();

Output

The above code will produce the following output −

XYZ
20

In the above output, users can observe that the console displays the value of the two fields' name and roll of the Person class.

Using static readonly property constants

In this method, in addition to the readonly keyword, we will also use the static keyword, allowing us to directly instantiate the constant property without first constructing a specific instance.

In other words, this class attribute would remain constant and not be assignable to the class constructor. For further simplicity, we will also declare here the static function that will show our result over the browser console and which doesn't call instantiation, for instance.

Example

In the below example, we can see that here we created a class named ‘Person’. It has a field called PersonName. It has a prefix of the readonly keyword along with the static keyword. That means we cannot update or modify the value of these fields outside and inside the constructor. It will display an error. After that, we create a function named displayName(), where we display the field value using the console. And this function is invoked by the Person class.

class Person {
   static readonly PersonName : string = "TutorialsPoint";
   static Displayname() : void {

      console.log(Person.PersonName);
   }
}
Person.Displayname();

On compiling, it will generate the following JavaScript code −

var Person = /** @class */ (function () {
   function Person() {
   }
   Person.Displayname = function () {
      console.log(Person.PersonName);
   };
   Person.PersonName = "TutorialsPoint";
   return Person;
}());
Person.Displayname();

Output

The above code will produce the following output −

TutorialsPoint

In the above output, users can observe that the console displays the value of the field PersonName of Person class.

Updated on: 19-Dec-2022

912 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements