📜  typescript ingerit - TypeScript (1)

📅  最后修改于: 2023-12-03 15:35:24.158000             🧑  作者: Mango

TypeScript Inheritance

Inheritance is an essential feature of object-oriented programming that allows a class to inherit properties and methods from another class. TypeScript, being an extension of JavaScript, also supports inheritance.

Syntax for declaring a class and inheritance in TypeScript:

class BaseClass {
  // base class properties and methods
}

class DerivedClass extends BaseClass {
  // class properties and methods
}

Here, BaseClass is the parent class, and DerivedClass is the child class. The extends keyword is used to inherit properties and methods from the parent class.

Access Modifiers

Access modifiers are used to control the visibility of properties and methods in a class. TypeScript provides three access modifiers:

  • public: Accessible to all.
  • private: Accessible only within the class.
  • protected: Accessible within the class and its subclasses.
class BaseClass {
  public name: string; // public property
  private age: number; // private property
  protected address: string; // protected property
  
  public printInfo() {
    console.log(`Name: ${this.name}, Age: ${this.age}, Address: ${this.address}`);
  }
}

class DerivedClass extends BaseClass {
  constructor() {
    super();
    this.name = 'John';
    this.age = 25; // Error: Property 'age' is private and only accessible within class 'BaseClass'.
    this.address = '123 Main St.';
  }
}

const obj = new BaseClass();
obj.name = 'Jane';
obj.age = 30; // Error: Property 'age' is private and only accessible within class 'BaseClass'.
obj.address = '456 Oak St.'; // Error: Property 'address' is protected and only accessible within class 'BaseClass' and its subclasses.

In the above example, name is a public property accessible from any class instance. age is a private property only accessible within the BaseClass. address is a protected property accessible within the BaseClass and its subclasses.

Method Overriding

Method overriding is the ability of a child class to provide its implementation of a method with the same name as the parent class.

class BaseClass {
  public printMessage() {
    console.log('This is the base class message');
  }
}

class DerivedClass extends BaseClass {
  public printMessage() {
    console.log('This is the derived class message');
  }
}

const obj1 = new BaseClass();
obj1.printMessage(); // This is the base class message

const obj2 = new DerivedClass();
obj2.printMessage(); // This is the derived class message

In the above example, printMessage method is overridden in the DerivedClass and provides its implementation.

Conclusion

Inheritance is a powerful feature of object-oriented programming that allows reusability of code. TypeScript provides support for inheritance, access modifiers, and method overriding, making it easier to create maintainable and readable codebases.