Open In App

What is Public Static Const in TypeScript ?

In TypeScript, there is no direct equivalent to a public static const declaration as you might find in some other languages. However, you can achieve similar behavior using a combination of the public, static, and readonly keywords.

Syntax:

class ClassName {
public static readonly CONSTANT_NAME: Type = InitialValue;
// Other members of the class...
}

Let’s break down what each of these modifiers does:



Example 1: In this example, the class MathConstants declares a public, static, and read-only constant named PI with the value 3.14159. The class also has a method calculateCircumference that uses the PI constant to calculate the circumference of a circle. The constant can be accessed using MathConstants.PI.




class MathConstants {
    public static readonly PI: number = 3.14159;
 
    calculateCircumference(radius: number): number {
        return 2 * MathConstants.PI * radius;
    }
}
 
// Example usage:
const mathInstance = new MathConstants();
const circumference = mathInstance
    .calculateCircumference(5);
console.log(`Circumference: ${circumference}`);

Output:



Circumference: 31.4159

Example 2: In this simple example, the SimpleExample class declares a public, static, and read-only constant named GREETING with the value "Hello, TypeScript!". The class also has a method printGreeting that prints the greeting to the console. The constant is accessed using SimpleExample.GREETING.




class SimpleExample {
    public static readonly GREETING:
        string = "Hello, TypeScript!";
 
    printGreeting(): void {
        console.log(SimpleExample.GREETING);
    }
}
 
// Example usage:
const instance = new SimpleExample();
instance.printGreeting();

Output:

Hello, TypeScript!

Article Tags :