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

Interface inheritance

As an example of interface inheritance, consider the following TypeScript code:

interface IBase { 
    id: number | undefined; 
} 
 
interface IDerivedFromBase extends IBase { 
    name: string | undefined; 
} 
 
class InterfaceInheritanceClass implements IDerivedFromBase { 
    id: number | undefined; 
    name: string | undefined; 
}

We start with an interface called IBase, which defines an id property, of type number or undefined. Our second interface definition, IDerivedFromBase, extends (or inherits) from IBase, and therefore automatically includes the id property. The IDerivedFromBase interface then defines a name property, of type string or undefined. As the IDerivedFromBase interface inherits from IBase, it therefore actually has two properties—id and name. We then have a class definition, named InterfaceInheritanceClass, that implements this IDerivedFromBase interface. This class must, therefore, define both an id and a name property in order to successfully implement all of the properties of the IDerivedFromBase interface. Although we have only shown properties in this example, the same rules apply for functions.