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

What is getters/setters in TypeScript?

Câu trả lời

In TypeScript, getters and setters are special methods used to define access to the properties of an object. These methods are also known as accessors and mutators, respectively.

Getters

A getter, or accessor, is a method that gets the value of a specific property. It does not take any parameters and returns a value. In TypeScript, you define a getter using the get keyword followed by a function. The primary purpose of a getter is to return the internal state of an object without the consumer directly accessing the private member variables.

Setters

A setter, or mutator, is a method that sets the value of a specific property. It takes one parameter (the new value to set) and does not typically return a value. In TypeScript, you define a setter using the set keyword followed by a function. Setters allow controlling how important values are updated in an object, which can include validation or even computation before the value is stored.

Example

Here is a simple example of how getters and setters can be implemented in TypeScript:

typescript Copy
class Person {
    private _name: string;

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

    get name(): string {
        return this._name;
    }

    set name(value: string) {
        if (value.length > 0) {
            this._name = value;
        } else {
            console.error("Invalid name.");
        }
    }
}

let person = new Person("John");
console.log(person.name); // John
person.name = "Steve"; // sets the name to S...
junior

junior

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

middle

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

junior

What is Type Erasure in TypeScript?

middle

Explain Project References and its benefits

Bình luận

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

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