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

List a few rules of private fields in TypeScript

Câu trả lời

Private fields in TypeScript, introduced in TypeScript 3.8, are designed to provide a stricter level of encapsulation in classes. Here are some of the key rules and characteristics of private fields in TypeScript:

  1. Syntax: Private fields are declared with a # character prefixing the field name. This character is part of the field's name and signifies that the field is private[1][3][4].

  2. Scope: Every private field name is uniquely scoped to its containing class. This means that the private field is only accessible within the class it is declared in, ensuring that its privacy is maintained[1].

  3. Accessibility Modifiers: TypeScript's accessibility modifiers like public or private cannot be used on these private fields. By definition, a field prefixed with # is always private and cannot be made public[1].

  4. Hard Privacy: Private fields enforce hard privacy, meaning they cannot be accessed or even detected from outside the containing class. This is in contrast to TypeScript's traditional private modifier, which only enforces privacy at compile time but not at runtime[1][2].

  5. Compatibility: To use private fields in TypeScript, your project needs to target ES2015 (ES6) or higher. This is because the transpilation of private fields relies on WeakMap for versions below ES2021, and directly as private fields in environments that support ES2021 or later[1][2].

  6. No Runtime Reflection: Unlike regular properties, private fields are not visible to methods like Object.getOwnPropertyNames and are not included in the output of JSON.stringify. This further reinforces their privacy[2].

  7. Inheritance Rules: TypeScript enforces that a private field declared in a subclass cannot have the same n...

middle

middle

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

entry

How to call base class constructor from child class in TypeScript?

junior

How can we use optional chaining in TypeScript?

junior

Which object oriented terms are supported by TypeScript?

Bình luận

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

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