Câu hỏi phỏng vấn Typescript
Câu hỏi

How to implement class constants in TypeScript?

Câu trả lời

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:

1. Using 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:

typescript Copy
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].

2. Using 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:

typescript Copy
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].

3. Using External Constants

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:

typescript Copy
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].

4. Using Enums

Enums can also be used to define constants, especially when the constants are r...

junior

junior

Gợi ý câu hỏi phỏng vấn

entry

Do we need to compile TypeScript files and why?

junior

What is Type Erasure in TypeScript?

middle

What is the default access modifier for members of a class in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào