Mastering TypeScript 3
上QQ阅读APP看书,第一时间看更新

Class inheritance

Classes can also use inheritance in the same manner as interfaces. Using our definitions of the IBase and IDerivedFromBase interfaces, the following code shows an example of class inheritance:

class BaseClass implements IBase { 
    id: number | undefined; 
} 
 
class DerivedFromBaseClass  
    extends BaseClass 
    implements IDerivedFromBase { 
        name: string | undefined; 
    } 

The first class, named BaseClass, implements the IBase interface, and as such, is only required to define a property of id, of type number or undefined. The second class, DerivedFromBaseClass, inherits from the BaseClass class (using the extends keyword), but also implements the IDerivedFromBase interface. As BaseClass already defines the id property required in the IDerivedFromBase interface, the only other property that the DerivedFromBaseClass class needs to implement is the name property. Therefore, we only need to include the definition of the name property in the DerivedFromBaseClass class.

TypeScript does not support the concept of multiple inheritance. Multiple inheritance means that a single class can be derived from multiple base classes. TypeScript only supports single inheritance and, therefore, any class can only have a single base class. A class can, however, implement multiple interfaces, as follows:

interface IFirstInterface { 
    id : number | undefined; 
} 
interface ISecondInterface { 
    name: string | undefined; 
} 
class MultipleInterfaces  
    implements IFirstInterface, ISecondInterface { 
    id: number | undefined; 
    name: string | undefined; 
}

Here, we have defined two interfaces named IFirstInterface and ISecondInterface. We then have a class named MultipleInterfaces that implements both IFirstInterface and ISecondInterface. This means that the MultipleInterfaces class must implement an id property to satisfy the IFirstInterface interface, and it must implement a name property to satisfy the ISecondInterface interface.