首页 文章

typescript字符串文字方法 - 重载事件

提问于
浏览
4

我一直在使用的一些类型定义声明了一些带字符串文字的方法重载 . 所以在环境d.ts文件中,我看到:

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

这会在VSCode中产生很好的智能,它将列出每个事件以及您需要为每个事件使用的不同函数覆盖 .

不幸的是,在普通的TypeScript中,不允许使用上面的字符串文字 . 您可以将字符串定义为类型...

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

...但是你不能声明只有这些字符串类型不同的方法重载 . 即你目前允许这样做:

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

有没有办法定义一个方法,以便它显示intellisense显示不同的事件名称和对应于这些事件的参数重载?

1 回答

  • 1

    实现这一点的正确方法是使用方法签名重载;你只能有一个方法实现:

    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*/
        }
      }
    }
    

相关问题