TypeScript中的extends和implements:有什么区别?
大家好!我刚开始在JavaScript之后学习TypeScript,对两个关键词——`extends`和`implements`感到困惑。它们似乎都用于类和接口,但我不明白何时该用哪个。
我有一个简单的接口`Animal`,它描述了基本属性和方法:
```typescript
interface Animal {
name: string;
makeSound(): void;
}
```
我想创建一个`Dog`类。在示例中,我看到既用了`extends`也用了`implements`:
```typescript
// 选项1:implements
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Woof!");
}
}
// 选项2:extends(如果有基类)
class AnimalBase {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends AnimalBase {
makeSound() {
console.log("Woof!");
}
}
```
但我不明白根本区别。什么时候使用