How to implement class constants in TypeScript?
How to implement class constants in TypeScript?
To implement class constants in TypeScript, you have several options depending on the specific requirements and the scope of the constants within your application. Here are the primary methods to define constants in a TypeScript class:
readonlyThe readonly keyword is used to make a class property immutable, meaning its value cannot be changed after it is initially set. This is the simplest way to implement constants within a class.
Example:
class Example {
readonly constantValue: number = 10;
}
In this example, constantValue is a constant within the Example class, and its value cannot be changed once it is initialized.
static readonlyIf you want the constant to be accessible without instantiating the class, you can use a combination of static and readonly. This makes the constant a static member, accessible directly from the class itself rather than from instances of the class.
Example:
class Example {
static readonly constantValue: number = 10;
}
console.log(Example.constantValue); // Outputs: 10
This method is useful when you need a constant value that should be the same across all instances of the class and accessible without creating an instance of the class.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.