推荐答案
在 TypeScript 中,接口可以通过继承来扩展其他接口的功能。通过继承,一个接口可以包含另一个接口的所有成员,并且可以在此基础上添加新的成员或重写现有成员。
// www.javascriptcn.com code example
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
const square: Square = {
color: "blue",
sideLength: 10,
};在这个例子中,Square 接口继承了 Shape 接口,因此 Square 接口包含了 color 属性,并且还添加了 sideLength 属性。
本题详细解读
接口继承的基本语法
接口继承使用 extends 关键字,语法如下:
interface ChildInterface extends ParentInterface {
// 新增的成员
}ChildInterface是子接口,它将继承ParentInterface的所有成员。ParentInterface是父接口,它的所有成员都会被ChildInterface继承。
多重继承
TypeScript 支持接口的多重继承,即一个接口可以同时继承多个接口:
// www.javascriptcn.com code example
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
const square: Square = {
color: "blue",
penWidth: 5,
sideLength: 10,
};在这个例子中,Square 接口同时继承了 Shape 和 PenStroke 接口,因此 Square 包含了 color、penWidth 和 sideLength 三个属性。
重写继承的成员
在接口继承中,子接口可以重写父接口中的成员类型,但必须保持兼容性:
// www.javascriptcn.com code example
interface Shape {
color: string;
}
interface Square extends Shape {
color: "blue" | "red"; // 重写 color 属性,限制为特定值
sideLength: number;
}
const square: Square = {
color: "blue", // 只能是 "blue" 或 "red"
sideLength: 10,
};在这个例子中,Square 接口重写了 Shape 接口中的 color 属性,将其类型限制为 "blue" | "red"。
接口继承与类实现
接口继承也可以用于类实现接口时:
// www.javascriptcn.com code example
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
class MySquare implements Square {
color: string;
sideLength: number;
constructor(color: string, sideLength: number) {
this.color = color;
this.sideLength = sideLength;
}
}在这个例子中,MySquare 类实现了 Square 接口,因此必须包含 color 和 sideLength 属性。