如何为扩展相同 class 的对象数组分配类型?

How can I assign types for an array of objects that extend the same class?

这可能是一个愚蠢的问题,因为我是打字稿的新手,但是,我有以下情况。我有一个数组,其中包含所有扩展相同 class 的对象。例如:

class Body{
 // implementation
}

class Rectangle extends Body{
 // implementation
}

class Circle extends Body{
 // implementation
}

const box: Rectangle = new Rectangle()
const circle: Circle = new Circle()

const world: Array<Body> = [box, circle]

我遇到的问题是,当我访问数组中元素的方法时,我收到一个错误,指出它们不存在于 Body class(它们不存在) .我想知道是否有正确的方法来做到这一点,或者我做的事情是否完全错误?

Array<Body>表示数组元素只保证实现Body接口

如果您想要一个 Body 实例数组,这些实例可能是子类,那么您必须先进行运行时检查以确保该对象符合您的预期。

const world: Array<Body> = [box, circle]

if (world[0] instanceof Rectangle) {
    world[0].someRectangleOnlyMethod()
}

这是必需的,因为这会崩溃,因为 Circle 个实例上不存在该方法:

world[1].someRectangleOnlyMethod() // crash

Playground

您应该尝试在 Body class 中创建可以由子class 实现的抽象方法。这样你会有不同的行为但相同的方法 - 多态性。 F.e.:

abstract class Body {
  abstract area(): number;
}

然后子classes可以有实现。

如果在不同的 class 中使用相同的方法名称没有意义,那么您必须检查对象的 class 和 instanceof,如 所说。

虽然在大多数情况下您确实需要 Alex Wayne 或 Uroš Anđelić 的方法,但也有

const world = [box, circle] as const;

在这种情况下,world 的类型将被推断为 [Box, Circle],您可以在 world[0].

上调用 Box 的方法