Skip to content

Subclassing is useless for generated classes #1

@mishok13

Description

@mishok13

If we are trying to subclass from generated class we need to quite literally overwrite all modifying objects. To illustrate, I'll take your example from readme (with some minor modifications, such as _data having protected modifier instead of private):

export class Circle {
  // snipped for brevity
  protected _data: any;
  constructor(data: any = {}) {
    this._data = data;
  }
  get uuid(): string {
    return this._data.uuid;
  }
  setUuid(uuid: string): Circle {
    const data = this._data.uuid = uuid;
    return new Circle(data);
  }
  // More snipping
}

If we are to subclass from this object, say like this

class OtherCircle extends Circle {
  get foo(): string {
    return this._data.foo;
  }
  setFoo(foo: string): OtherCircle {
    const data = this._data.foo = foo;
    return new OtherCircle(data);
  }
}

Then trying to use this in the following piece of code will lead to type error:

let other: OtherCircle = new OtherCircle();
other = other.setUuid('bar'); // triggers TSError with message "Type 'Circle' is not assignable to type 'OtherCircle'."

Very often however we'll use const modifiers, which will mask the issue and lead to very nasty bugs later on:

const other: OtherCircle = new OtherCircle();
console.log(other instanceof OtherCircle); // true
const otherWithFoo = other.setFoo('bar');
console.log(otherWithFoo instanceof OtherCircle); // true, seems correct
const otherWithBar = other.setUuid('bar');
console.log(otherWithBar instanceof OtherCircle); // false !!!

I hope this explains what the issue is.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions