fe-interview
fe-interview copied to clipboard
[TypeScript] extends 和 implements 有什么区别?
extends是继承某个类,继承后可以使用父类的方法,也可以重写父类的方法。 implement是接口约束,约束要重写父类的方法
在 TypeScript 中,extends 和 implements 都用于类的继承和实现,但它们有不同的用途和行为。以下是它们的区别和用法详细说明:
extends
extends 关键字用于类的继承。一个类可以通过 extends 关键字继承另一个类,这意味着子类将继承父类的所有属性和方法。子类还可以覆盖父类的方法。
使用 extends 的示例
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance} meters.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog('Buddy');
dog.bark(); // 输出: Woof! Woof!
dog.move(10); // 输出: Buddy moved 10 meters.
在这个例子中,Dog 类通过 extends 关键字继承了 Animal 类的属性和方法。
implements
implements 关键字用于实现接口。一个类可以通过 implements 关键字实现一个或多个接口,这意味着该类必须定义接口中所有声明的方法和属性。接口仅用于描述类的结构,它不会提供任何具体的实现。
使用 implements 的示例
interface Animal {
name: string;
move(distance: number): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number) {
console.log(`${this.name} moved ${distance} meters.`);
}
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog('Buddy');
dog.bark(); // 输出: Woof! Woof!
dog.move(10); // 输出: Buddy moved 10 meters.
在这个例子中,Dog 类通过 implements 关键字实现了 Animal 接口,并且必须提供接口中声明的 move 方法和 name 属性。
区别总结
-
用途:
extends用于类的继承,子类继承父类的所有属性和方法。implements用于类实现接口,类必须实现接口中声明的所有方法和属性。
-
继承关系:
extends是类和类之间的继承关系。implements是类和接口之间的实现关系。
-
多个继承/实现:
- 在 TypeScript 中,一个类只能继承一个类(单继承)。
- 一个类可以实现多个接口(多实现)。
-
接口的实现:
- 接口只能通过
implements关键字来实现,不能通过extends关键字继承。 - 一个接口可以继承另一个接口或多个接口。
- 接口只能通过
接口继承示例
interface Movable {
move(distance: number): void;
}
interface Eatable {
eat(food: string): void;
}
interface Animal extends Movable, Eatable {
name: string;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number) {
console.log(`${this.name} moved ${distance} meters.`);
}
eat(food: string) {
console.log(`${this.name} ate ${food}.`);
}
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog('Buddy');
dog.bark(); // 输出: Woof! Woof!
dog.move(10); // 输出: Buddy moved 10 meters.
dog.eat('bone'); // 输出: Buddy ate bone.
总结
extends用于类的继承,允许子类继承父类的属性和方法。implements用于类实现接口,要求类实现接口中定义的所有方法和属性。- 一个类只能继承一个类,但可以实现多个接口。