What is Public Static Const in TypeScript ?
Last Updated :
05 Jan, 2024
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:
public
: This keyword declares that the constant is accessible from outside the class. It means that the constant can be accessed by instances of the class as well as from outside the class.
static
: The static
the keyword indicates that the constant is associated with the class itself, not with instances of the class. It means you can access the constant using the class name without creating an instance. For example, if you have a class MyClass
with a static constantMY_CONSTANT
, you can access it MyClass.MY_CONSTANT
without creating an instance of MyClass
.
readonly
: This keyword specifies that the constant cannot be reassigned after it is initialized. Once a value is assigned to a readonly
property or constant, it cannot be changed. This ensures that the constant maintains its initial value throughout the program.
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
.
Javascript
class MathConstants {
public static readonly PI: number = 3.14159;
calculateCircumference(radius: number): number {
return 2 * MathConstants.PI * radius;
}
}
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
.
Javascript
class SimpleExample {
public static readonly GREETING:
string = "Hello, TypeScript!" ;
printGreeting(): void {
console.log(SimpleExample.GREETING);
}
}
const instance = new SimpleExample();
instance.printGreeting();
|
Output:
Hello, TypeScript!
Share your thoughts in the comments
Please Login to comment...