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

What is the difference between Private and Protected variables in TypeScript?

Câu trả lời

In TypeScript, the difference between private and protected variables pertains to their accessibility within classes and their subclasses.

Private Variables

Private variables in TypeScript are accessible only within the class where they are declared. They cannot be accessed from outside of this class, not even from classes that inherit from this class. This strict access control is useful for encapsulating sensitive data or implementation details that should not be exposed outside of the class.

For example, if a class Person has a private variable age, this variable can only be accessed by methods within the Person class. Attempting to access this variable from outside the class, or from a subclass, will result in a compilation error.

typescript Copy
class Person {
    private age: number;

    constructor(age: number) {
        this.age = age;
    }

    displayAge() {
        console.log(this.age);
    }
}

const person = new Person(30);
person.displayAge(); // Works
console.log(person.age); // Error: 'age' is private and only accessible within class 'Person'.

Protected Variables

Protected variables, on the other hand, are similar to private variables but with a less restrictive level of access control. Protected variables are accessible within the class in which they are declared as well as by instances of classes that inherit from this class.

This means that if a class Employee extends the Person class, it can access any protected variables declared in Person.

typescript Copy
class Person {
    protected name: string;

    constructor(name: string) {
        this.name = name;
    }
}

class Employee extends Person {
    constructor(name: string) {
       ...
middle

middle

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

middle

What is the fundamental difference between Optional Chaining ( ?. ) and Non-null assertion operator ( ! )
in TypeScript?

middle

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

middle

Why do we need to use abstract keyword for classes and their methods in TypeScript?

Bình luận

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

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