In TypeScript, class constants can be implemented in several ways, with the most common approach being the use of the static readonly modifier. The static keyword indicates that the property or method belongs to the class itself rather than to instances of the class, while readonly ensures that the property's value cannot be modified after initialization (read-only property).
Below is an example using static readonly to define a class constant:
typescriptclass MyClass { static readonly CONSTANT_VALUE: number = 10; displayConstant() { console.log(MyClass.CONSTANT_VALUE); } } const example = new MyClass(); example.displayConstant(); // Output: 10 // Attempting to modify the constant value results in a compilation error // MyClass.CONSTANT_VALUE = 20; // Error: Cannot assign to 'CONSTANT_VALUE' because it is a read-only property
In this example, CONSTANT_VALUE is a constant defined as a static read-only property of the MyClass class. This means we can access the property directly through the class name without creating an instance. Additionally, the readonly modifier ensures the property value remains immutable, preserving its constant nature.
This approach is ideal for data that needs to be shared at the class level and remains unchanged, such as configuration values or error codes. It ensures data consistency and maintains class encapsulation.