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:
readonly
The 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[2][4].
static readonly
If 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[2][4].
For constants that are used across different classes or modules, you can declare them outside of the class and then use them wherever needed.
Example:
const CONSTANT_VALUE: number = 10;
class Example {
getConstant() {
return CONSTANT_VALUE;
}
}
This approach is beneficial when the same constant value is required in multiple classes or parts of the application[2].
Enums can also be used to define constants, especially when the constants are r...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào