重学TS中的继承、实现

一,extends(继承)

在TypeScript中,extends关键字用于类或接口的继承。它允许一个类或接口继承另一个类或接口的成员。

1. 接口继承(interface extends)

typescript

interface Shape {
color: string;
}

interface Square extends Shape {
sideLength: number;
}

这里Square接口继承了Shape接口,所以Square将有colorsideLength两个属性。

2. 类继承(class extends)

typescript

class Animal {
move() {
console.log("Moving...");
}
}

class Dog extends Animal {
bark() {
console.log("Woof!");
}
}

Dog类继承自Animal类,因此拥有move方法,同时自己定义了bark方法。


二、implements(实现)

implements关键字用于类实现接口。当一个类实现一个接口时,它必须包含接口中定义的所有成员。

typescript

interface Animal {
name: string;
makeSound(): void;
}

class Dog implements Animal {
name: string;

constructor(name: string) {
this.name = name;
}

makeSound() {
console.log("Woof!");
}
}

Dog类实现了Animal接口,因此必须包含name属性和makeSound方法。