How to handle inherited classes with different paramters in same name function (such as "initialize") in TypeScript?

34 views Asked by At

I'm rewriting an old js file to ts file. It uses some es5-time tricks to create a inherited class:

function Sprite_Button() {
    this.initialize(...arguments);
}

Sprite_Button.prototype = Object.create(Sprite_Clickable.prototype);
Sprite_Button.prototype.constructor = Sprite_Button;

Sprite_Button.prototype.initialize = function(){
  Sprite_Clickable.prototype.initialize.call(this)
}

It uses initialize to replace the use of the class constructor. However, if a inherited class want to be somewhat different, such as adding a parameter like "index", now the initialize function looks like: initialize(index:number):void; this will cause a error, saying that "is not assignable to the same property in base type" if is in construcor, this won't be a problem.

The contructor has a every good feature, that it just requires calling the super in the current constructor, and it's no need to let the base class's constructor has the same parameters as the derived class's(maybe because they are different functions after all, it's special)

This is a rewriting of these code, for example:

class Sprite{
  _bitmap: Bitmap;
  constructor(){
  }
  initialize():void{
    // some code actions like a constructor
    this._bitmap = new Bitmap(640, 320); 
  }
}

class Sprite_Button extends Sprite{
  _buttonType: string;
  constructor(){
  }

  // print error 
  override initialize(buttonType: string){
    super.initialze();
    this._buttonType = buttonType;
  }
}

I want to keep the design of the duplicate name with different params of the initialize, is there any ts description could cover the scene? ps: Or expecting some configs in tsconfig.json to disable this check. (I can't imagine the influence, maybe it's not a good choice)

0

There are 0 answers