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

What are the differences between the privat...

Câu trả lời

In TypeScript, both the private keyword and private fields (denoted by #) are used to restrict access to class members, but they differ significantly in their enforcement and compatibility levels.

Private Keyword

The private keyword in TypeScript is used to indicate that a class member should not be accessible from outside of its containing class. This is enforced at compile time, meaning TypeScript will generate an error during the compilation process if a private member is accessed from outside its class. However, this restriction is only present in the TypeScript environment.

  • Compile-time checking: The TypeScript compiler checks access to private members and throws an error if a member is accessed from outside its class.
  • No runtime enforcement: When TypeScript code is transpiled to JavaScript, the private keyword does not translate into any equivalent JavaScript functionality. This means that the privacy of members is not enforced at runtime, and such members are technically accessible in the resulting JavaScript[1][3].

Private Fields

Private fields, introduced in ECMAScript 2021 and available in TypeScript, use the # prefix to denote a private class member. Unlike the private keyword, private fields are enforced both at compile-time and at runtime.

  • Runtime privacy: Private fields maintain their privacy in JavaScript, meaning they cannot be accessed from outside the class even after the TypeScript code has been transpiled to JavaScript. This is because the # syntax is part of the JavaScript language and is understood by JavaScript engines[1][3].
  • Strong encapsulation: Access to private fields is restricted in such a way that they are not visible to code outside the class, not even through JavaScript functions like Object.getOwnPropertyNames or JSON.stringify, which can typically access properties defined on an object[1].

Key Differences

  1. Enforcement: The private keyword is only enforced by the TypeScript compil...
expert

expert

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

middle

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

middle

How to make a readonly tuple type in TypeScript?

entry

Explain generics in TypeScript

Bình luận

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

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