0

Try to understand the best way to overload methods in TypeScript classes and come with extends error while compiling.

There's an abstract class :

export abstract class Collection {
  protected _collection: any;

  public hydrate(key: number, item: Object): Collection;
  public hydrate(key: any, item: any): Collection {
    this._collection.set(key, item);
    return this;
  }

  public size(): number {
    return this._collection.size;
  }
}

And the concrete class :

export class Tours extends Collection {

  public constructor() {
    super();

    this._collection = new Map();
  }

  public hydrate(key: number, item: Tour) {
    this._collection.set(key, item);  
  }
}

Compilation failed with an error on the types of the concrete class (number and Tour) that are not assignable to number and Object of the parent method.

As the Tour type is a custom type, don't know how implement correctly this classes scheme...

How to do that ?

Jean-Luc Aubert
  • 620
  • 5
  • 19
  • Why not use OR operator: `public hydrate( key: number | any, item: any | Tour }`. Here's the question that solves this: https://stackoverflow.com/questions/12776625/can-i-specify-parameter-type-as-one-of-many-types-instead-of-any-type-in-typescr#32263803 – Z. Bagley Jan 31 '18 at 16:03
  • Might want to use generics for this kind of thing – Frank Modica Jan 31 '18 at 16:11

1 Answers1

2

You need to preserve the original signature as well:

public hydrate(key: number, item: Object) : Collection
public hydrate(key: number, item: Tour) : Collection
public hydrate(key: number, item: Tour) {
    return this._collection.set(key, item);
}

In your case however I would recommend making Collection generic:

export abstract class Collection<T> {
    protected _collection: Map<number, T>;

    public hydrate(key: number, item: T): this {
        this._collection.set(key, item);
        return this;
    }
    ...
}

export class Tours extends Collection<Tour> { }
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357