实现说明
活动部件是函数 renderCircle。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 renderCircle。
主要签名是 const renderCircle = (shape: Circle)
核心语句
const anyShapePainter: Painter = { paint: (shape: Shape) => `shape ${shape.name}` };
const renderCircle = (shape: Circle): string => `circle r=${shape.radius}`;
paint: (shape: Shape) => string;
代码示例
interface Shape {
name: string;
}
interface Circle extends Shape {
radius: number;
}
const renderCircle = (shape: Circle): string => `circle r=${shape.radius}`;
// Property signature: strictFunctionTypes checks parameters contravariantly,
// so a paint that only knows Circle cannot sit behind a Shape contract.
interface Painter {
paint: (shape: Shape) => string;
}
const anyShapePainter: Painter = { paint: (shape: Shape) => `shape ${shape.name}` };
// @ts-expect-error — renderCircle only accepts Circle, too narrow for Painter
const narrowPainter: Painter = { paint: renderCircle };
// Method shorthand: bivariant parameter checking, so the narrow param slips through.
interface MethodPainter {
paint(shape: Shape): string;
}
const methodPainter: MethodPainter = {
paint(shape: Circle): string {
return renderCircle(shape);
},
};
const unit: Circle = { name: 'unit', radius: 2 };
console.log(anyShapePainter.paint(unit));
console.log(narrowPainter.paint(unit));
console.log(methodPainter.paint(unit));