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

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

Câu trả lời

In TypeScript, to call a base class constructor from a child class, you use the extends keyword to establish inheritance between the two classes. Then, within the constructor of the child class, you call the base class constructor using the super() function. This approach ensures that the base class's constructor is executed, setting up the necessary properties or executing any logic defined there before the child class's constructor logic is executed.

Here’s a step-by-step explanation and an example:

Step-by-Step Explanation

  1. Define the Base Class: First, you define your base class with its constructor. This constructor can initialize properties or include other setup logic that you want to be executed when an instance of the base class or any derived class is created.

  2. Create the Child Class: Define the child class that extends the base class using the extends keyword. This establishes a relationship where the child class inherits properties and methods from the base class.

  3. Call the Base Class Constructor: Inside the constructor of the child class, use the super() function to call the constructor of the base class. The arguments passed to super() should match the parameters expected by the base class constructor.

  4. Additional Logic in the Child Constructor: After calling super(), you can add any additional initialization logic that is specific to the child class.

Example

class Person {
    constructor(private firstName: string, private lastName: string) {
        console.log("Person constructor called");
    }

    getFullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }
}

class Employee extends Person {
    private jobTitle: strin...
entry

entry

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

junior

What are assertion functions?

junior

What is a TypeScript Map file?

senior

What is dynamic import expression?

Bình luận

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

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