Search code examples
typescriptclassinheritancesubclass

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


I'm converting some C# code from a book into TypeScript and I've arrived at a problem I don't fully understand and have not been able to find the answer here or in the TypeScript docs, etc.

My code defined 2 classes, a base class Entity and a subclass Actor. The Actor class inherits 'name' and 'description' from Entity, both are strings, and it adds its own property 'location' which is a number. However TypeScript complains and says location should be a string. Why?

Here is the code:

/**
 * 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;
  }
}

Here is a screenshot of the error I get (using VS Code):

error message


Solution

  • My mistake.

    I misnamed the setter in Entity.