Is it possible to extend string parameter overloads on classes, like in interfaces?

Topics: General
Jul 2, 2014 at 12:30 AM
Edited Jul 2, 2014 at 12:31 AM
What I'd like to accomplish is have an event registration method implemented on a base class, and provide more specific overload declarations on subclasses. Something like the following:
class BaseEvent {
}

class FirstEvent extends BaseEvent {
}

class OtherEvent extends BaseEvent {
}


class Foo
{
    on(event: "first", handler: (ev: FirstEvent) => void): void;
    on(event: string, handler: (ev: BaseEvent) => void): void;
    on(event, handler): void {
    }
}



class Bar extends Foo {
    on(event: "other", handler: ( ev: OtherEvent ) => void): void;
    on(event: string, handler: any): void;
    on(event, handler): void { super.on(event, handler) }  // must have an implementation
}


var b = new Bar();
b.on(...)
The above only indicates 2 overloads for the "on" method on the Bar class. I'd like for it see three. Ideally, I'd like to define the Bar class like this:
class Bar extends Foo {
    on(event: "other", handler: ( ev: OtherEvent ) => void): void;
}
Jul 3, 2014 at 4:20 AM
You cannot do that. You'll have to copy-paste the overloads from Foo and add to it.
Jul 3, 2014 at 4:26 AM
Edited Jul 3, 2014 at 4:27 AM
This may be the closest you can get:
lass BaseEvent {
}

class FirstEvent extends BaseEvent {
}

class OtherEvent extends BaseEvent {
}

interface IFoo {
    on(event: "first", handler: (ev: FirstEvent) => void): void;
    on(event: string, handler: (ev: BaseEvent) => void): void;
}
class Foo implements IFoo
{
    on(event, handler): void {
    }
}

class Bar extends Foo {
}
interface IFoo { // (extend the interface)
    on(event: "other", handler: ( ev: OtherEvent ) => void): void;
}

var b: IFoo = new Bar();
Jul 3, 2014 at 4:31 AM
Edited Jul 3, 2014 at 4:31 AM
A possible other way:
class BaseEvent {
}

class FirstEvent extends BaseEvent {
}

class OtherEvent extends BaseEvent {
}

enum MyEvents {
    First = <MyEvents><any>"first",
    Second = <MyEvents><any>"second",
}

class Foo
{
    on(event: MyEvents, handler: (ev: BaseEvent) => void): void {
    }
}

enum MyEvents {
    Other = <MyEvents><any>"other"
}

class Bar extends Foo {
}

var b: Bar = new Bar();