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

Explain the difference between d...

Câu trả lời

In TypeScript, both declare enum and declare const enum are used to define enums without initializing them, which is particularly useful when you want to describe the shape of an enum that is defined elsewhere, such as in a JavaScript library or another TypeScript file. However, there are key differences between the two in terms of their compilation behavior and usage scenarios.

Declare Enum

The declare enum is used to define an enum without initializing it. This is useful when the enum is actually defined in another file or a third-party library, and you only need to reference it in your TypeScript code. The declare enum does not generate any JavaScript code during the TypeScript compilation process. It only serves as a type hint in TypeScript files, ensuring type safety and code completion during development.

For example:

typescript Copy
declare enum Status {
    Pending,
    InProgress,
    Completed
}

In this case, TypeScript understands the structure of Status but does not output any JavaScript for it.

Declare Const Enum

The declare const enum is similar to declare enum but with an added optimization hint. By using const, you are telling TypeScript that this enum is a constant and will not change. TypeScript can then perform an optimization by inlining the enum values at compile time. This means that wherever the enum is used, TypeScript will replace the enum reference with the actual value, reducing runtime overhead but at the cost of losing the enum structure in the compiled JavaScript.

For example:

typescript Copy
declare const enum Directions {
    Up,
    Down,
    Left,
    Right
}

If you use Directions.Up in your code, TypeScript will replace it with 0 during compilation, assuming no initial values are altered.

Key Differences

  1. Compilation Output: declare enum does not produce any JavaScript code, just like declare const enum. However, the key difference is in how they are treated by the TypeScript compiler regarding inlining:
    • declare enum keeps the enum as a reference, which means the actual value is not replaced during compilation.
    • `declare c...
expert

expert

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

senior

Why is the infer keyword needed in TypeScript?

middle

What are some use cases of template literal types in TypeScript?

junior

What is the purpose of Nullish Coalescing operator?

Bình luận

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

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