MST

星途 面试题库

面试题:TypeScript交叉类型与接口融合时的类型推导与约束

定义一个接口`Shape`,有`color: string`属性。再定义一个交叉类型`Rectangle`,有`width: number`和`height: number`属性。现在要融合`Shape`与`Rectangle`,并且创建一个函数`draw`,该函数接收融合后的类型作为参数,并根据形状的宽高和颜色在控制台打印出相应图形信息(例如:一个红色的宽10高20的矩形)。同时要保证传入的参数如果缺少任何必要属性,TypeScript能给出类型错误提示,请问该如何实现?
28.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义接口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}的矩形`);
}

在上述代码中:

  1. 首先定义了接口Shape,它有一个string类型的color属性。
  2. 接着定义了交叉类型Rectangle,它有number类型的widthheight属性。
  3. 然后通过交叉类型&ShapeRectangle融合为ShapeRectangle
  4. 最后定义draw函数,接收ShapeRectangle类型的参数,并按照要求在控制台打印出图形信息。如果传入的参数缺少colorwidthheight中的任何一个属性,TypeScript会给出类型错误提示。