Typescript 错误 ts2416 向子类添加 prop 导致 type no assignable 错误

Typescript error ts2416 adding prop to subclass causes type no assignable error

我正在将书中的一些 C# 代码转换为 TypeScript,但我遇到了一个我不完全理解的问题,并且无法在此处或 TypeScript 文档等中找到答案。

我的代码定义了 2 个 classes,一个基础 class 实体和一个子 class Actor。 Actor class 继承了 Entity 的 'name' 和 'description' ,都是字符串,并且它添加了自己的 属性 'location' 这是一个数字。然而 TypeScript 抱怨说 location 应该是一个字符串。为什么?

代码如下:

/**
 * base class
 */
export class Entity {
  private _name: string;
  private _description: string;

  protected constructor(aName:string, aDescription:string) {
    this._name = aName;
    this._description = aDescription;
  }

  get name(): string {
    return this._name;
  }

  set location(newName: string) {
    this._name = newName;
  }

  get description(): string {
    return this._description;
  }

  set description(newDescription: string) {
    this._description = newDescription;
  }
}

/**
 * subclass
 */
export class Actor extends Entity{
  private _location:number;

  public constructor(aName:string, aDescription:string, aRoom:number) {
    super(aName, aDescription)
    this._location = aRoom;
  }

  get location(): number {
    return this._location;
  }

  set location(newRoom: number) {
    this._location = newRoom;
  }
}

这是我得到的错误的屏幕截图(使用 VS Code):

我的错误。

我在实体中给 setter 取了错误的名字。