我有以下代码:
const enum ShapeType {
Circle,
Rectangle
}
class Shape {
constructor(public shapeType: ShapeType) {}
}
class Circle extends Shape {
constructor(public x: number, public y: number, public r: number) {
super(ShapeType.Circle);
}
}
class Rectangle extends Shape {
constructor(public x: number, public y: number, public w: number, public h: number) {
super(ShapeType.Rectangle);
}
}
function handleRectangleRectangleCollision(r1: Rectangle, r2: Rectangle) {
return Helpers.doRectanglesCollide(r1.x, r1.y, r1.w, r1.h, r2.x, r2.y, r2.w, r2.h)
}
function handleRectangleCircleCollision(r: Rectangle, c: Circle) {
return Helpers.circleRectangleCollision(c.x, c.y, c.r, r.x, r.y, r.w, r.h);
}
function handleCircleCircleCollision(c1: Circle, c2: Circle) {
return Helpers.circlesCollide(c1.x, c1.y, c1.r, c2.x, c2.y, c2.y);
}
function handleCircleRectangleCollision(c: Circle, r: Rectangle) {
return Helpers.circleRectangleCollision(c.x, c.y, c.r, r.x, r.y, r.w, r.h);
}
export let colliderMapping = {
[ShapeType.Rectangle]: {
[ShapeType.Rectangle]: handleRectangleRectangleCollision,
[ShapeType.Circle]: handleRectangleCircleCollision
},
[ShapeType.Circle]: {
[ShapeType.Circle]: handleCircleCircleCollision,
[ShapeType.Rectangle]: handleCircleRectangleCollision
}
}
function doShapesCollide(s1: Shape, s2: Shape) {
let colliderFn = colliderMapping[s1.shapeType][s2.shapeType];
return colliderFn(s1, s2);
}
我在最后一个最后一个错误:
return colliderFn(s1, s2);
Argument of type 'Shape' is not assignable to parameter of type 'Rectangle & Circle'.
Type 'Shape' is missing the following properties from type 'Rectangle': x, y, w, h
我明白为什么我会收到错误(我认为),但我不知道如何解决它。我基本上是想通过一个映射变量来实现一种干净的双重调度方式,这样每个形状组合都会返回一个有效的函数,我可以调用它来查看它们是否发生冲突。
有没有办法做到这一点?如果是这样,怎么做?