Class implementation interface
A class implements an interface, just like the basic function of an interface in Java.
A demo
// Animal interface interface Animal { type: string; sound: string; voice():void; } // Dog class implementation interface class Dog implements Animal { type:string; sound: string; voice():void { console.log(`${this.sound}, I am ${this.type}`) } constructor(sound: string,type: string) { this.sound = sound this.type = type } } // Cat class implementation interface class Cat implements Animal { type: string; sound: string; voice(): void { console.log(`${this.sound}, I am ${this.type}`) } constructor(sound:string, type: string) { this.sound = sound; this.type = type; } } new Cat("Meow meow~","Mammals").voice(); new Dog("Wang Wang~","Mammals").voice();
Print results:
Meow, meow. I'm a mammal. Wang Wang, I'm a mammal
Inheritance interface
Interfaces can inherit from each other
A demo
// Biological interface interface Creature { name: string; } // Animal interface inherits biological interface interface Animal extends Creature { // Own attribute action action(): void; } class Dog implements Animal { name: string; // name is inherited from the feature by Animal. If it is not implemented, an error will be reported. action(): void { console.log(`I am ${this.name}`) } constructor (name: string) { this.name = name; } } new Dog("Doggy").action() // I am a dog.
Class must implement all the properties of its interface, including the properties it inherits from its parent class
㈐ in addition: multiple interfaces can be inherited: one interface can inherit multiple interfaces
A demo
// Biological interface interface Creature { name: string; } // Animal interface interface Animal { // Own attribute action action(): void; } // Dog interface inherits Creature creation and Animal multiple inheritance interface Dog extends Creature, Animal{ color: string; } class Golden implements Dog { name: string; color: string; action():void { console.log(`I am ${this.name},My color is ${this.color}`) } constructor(name: string, color:string) { this.name = name; this.color = color; } } new Golden("Golden hair","Golden").action() // I'm golden. My color is golden.
Golden implements the Dog interface. The Dog interface mostly inherits the two interfaces of creation and Animal, and has their properties, so golden needs to implement them all.