4

Some typing definitions I've been using have declared some method overloads with string literals. So in an ambient d.ts file, I've seen:

on(event: string, listener: Function): this;
on(event: 'endTag', listener: (name: string, location?: LocationInfo) => void): this;

and this results in nice intellisence in VSCode that will lists each event and the different function overrides you need to use for each of them.

Unfortunately in normal TypeScript you are not allowed to use string literals like above. You can define a string as a type...

export type Open = "open";
export type Close = "close";
export type Error = "error";

...but you cannot declare method overloads that only differ by these string types. i.e. you are not allowed to do this at present:

on(event:Open, cb:()=>void){}
on(event:Close, cb:()=>void){}
on(event:Error, cb:(e:string)=>void){}

Is there a way to define a method so that it brings up intellisense showing the different event names and the parameter overloads corresponding to those events?

1 Answer 1

2

The correct way to implement this is to use method signature overloading; you can only have one method implementation though:

export class Client {
  on(event: "open", cb: () => void)
  on(event: "close", cb: () => void)
  on(event: "error", cb: (err: Error) => void)
  on(event: string, cb: Function) {
    switch (event) {
      /*add handlers*/
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.