打字稿:实现具有3种不同签名的界面的方法?

时间:2017-08-04 10:54:33

标签: node.js typescript winston

我试图在winston(节点登录框架)中包含一个函数/方法,我找到了它的接口

interface LeveledLogMethod {
    (msg: string, callback: LogCallback): LoggerInstance;
    (msg: string, meta: any, callback: LogCallback): LoggerInstance;
    (msg: string, ...meta: any[]): LoggerInstance;
}

我想实现一个名为“error”的方法,该方法将采用上述签名。

我只包装它,所以我将直接调用winston函数。

如果有人熟悉winston,我基本上有2个记录器设置,所有消费者都通过我的主要loglog类,我使用第一个记录器或第二个记录器,具体取决于loglevel,所以我需要包装它。

2 个答案:

答案 0 :(得分:2)

You can use optional properties and types to add that to your function so it matches the interface.

For example:

interface LeveledLogMethod {
    (msg: string, callback: () => void): string;
    (msg: string, meta: any, callback: () => void): string;
    (msg: string, ...meta: any[]): string;
}

let error: LeveledLogMethod = function (msg: string, b: () => void | any, c?: () => void): string {
    return '';
}

答案 1 :(得分:1)

Use 3 interfaces this way:

interface A {}
interface B {}
interface C {}

const variable: A|B|C = {};