Javascript 如何在typescript中实现具有多个匿名函数的接口

Javascript 如何在typescript中实现具有多个匿名函数的接口,javascript,node.js,typescript,Javascript,Node.js,Typescript,我正在尝试用typescript实现下面所示的接口 interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...meta: any[]): void; (message: any): void; (infoObje

我正在尝试用typescript实现下面所示的接口

interface A{
  (message: string, callback: CustomCallBackFunction): void;
  (message: string, meta: any, callback: CustomCallBackFunction): void;
  (message: string, ...meta: any[]): void;
  (message: any): void;
  (infoObject: object): void;
} 
这里是CustomCallBackFunction定义

type CustomCallBackFunction= (error?: any, level?: string, message?: string, meta?: any) => void;
我无法实现与类的接口。你知道怎么做吗

这是用于方法重载的 例如,我有一个B类,其变量类型为a,实现引用了所有其他选项

class B {
public c: A
}
然后我可以打电话

const b =new B();
b.c(message,callback);
b.c(message,meta,callback);
b.c(message,meta);
b.c(infoObject);

遗憾的是,实现此接口的唯一方法是使所有参数
any

这个接口很像,这意味着实现函数必须接受一个参数,该参数是该位置参数的所有可能性的并集

  • 第一个参数是
    字符串
    字符串
    字符串
    任何
    对象
    。因此类型是
    string | object | any
    ,它简化为
    any
    ,因为
    any
    包含其他可能性

  • 第二个参数是
    CustomCallBackFunction | any | undefined
    ,它也是
    any

  • 第三个参数可以是
    CustomCallBackFunction
    …meta:any[]
    的第二项,所以这一项也是
    any


  • 因此,鉴于所有参数必须是
    any
    类型,并且可能有任意数量的参数,我认为唯一有效的实现签名是:

    const fn: A = (...args: any[]) => {}
    
    然后,您必须自己测试每个参数的类型,并找出每个参数的含义以及使用的调用签名。是的,那太糟糕了

    const fn: A = (...args: any[]) => {
        if (args.length === 2 && typeof args[0] === 'string' && typeof args[1] === 'function') {
            // (message: string, callback: CustomCallBackFunction): void;
            const [message, callback] = args as [string, CustomCallBackFunction]
        } else if (args.length === 3 && typeof args[0] === 'string' && !Array.isArray(args[1]) && typeof args[2] === 'function') {
            // (message: string, meta: any, callback: CustomCallBackFunction): void;
            const [message, meta, callback] = args as [string, any, CustomCallBackFunction]
        } else {
            // etc...
        }
    }
    

    有趣的问题是,我玩了一些游戏,没有找到一个通过接口实现匿名函数的好解决方案。为什么它们需要匿名?这里的实际问题/错误是什么?每个具有兼容的调用签名集的函数都实现接口。实现不是语法的函数,例如类型注释或implements关键字的函数。它是隐式的,因为语言是结构类型化的,而不是名义类型化的。因此,我认为这是一个糟糕的解决方案,因为为了声明类型和使用显式类型注释而降低了类型安全性,这是一个糟糕的交易。