面试题答案
一键面试// 定义接口Shape
interface Shape {
color: string;
}
// 定义交叉类型Rectangle
type Rectangle = {
width: number;
height: number;
};
// 融合Shape与Rectangle
type ShapeRectangle = Shape & Rectangle;
// 创建draw函数
function draw(shape: ShapeRectangle) {
console.log(`一个${shape.color}的宽${shape.width}高${shape.height}的矩形`);
}
在上述代码中:
- 首先定义了接口
Shape
,它有一个string
类型的color
属性。 - 接着定义了交叉类型
Rectangle
,它有number
类型的width
和height
属性。 - 然后通过交叉类型
&
将Shape
和Rectangle
融合为ShapeRectangle
。 - 最后定义
draw
函数,接收ShapeRectangle
类型的参数,并按照要求在控制台打印出图形信息。如果传入的参数缺少color
、width
或height
中的任何一个属性,TypeScript会给出类型错误提示。