Home > Back-end >  How to create a class implementing an interface with a nameless function in Typescript?
How to create a class implementing an interface with a nameless function in Typescript?

Time:12-22

I am trying to mock a class implementing @azure/functions.Logger for unit tests in my Typescript app. The interface definition is

export interface Logger {

    /**

     * Writes streaming function logs at the default trace level.

     */

    (...args: any[]): void;

    /**

     * Writes to error level logging or lower.

     */

    error(...args: any[]): void;

    /**

     * Writes to warning level logging or lower.

     */

    warn(...args: any[]): void;

    /**

     * Writes to info level logging or lower.

     */

    info(...args: any[]): void;

    /**

     * Writes to verbose level logging.

     */

    verbose(...args: any[]): void;

}

I try

class SuperLogger implements Logger {

  error(...args: any[]): void {
     console.log('jdfnjskn');
  }
  warn(...args: any[]): void {
      throw new Error('Method not implemented.');
  }
  info(...args: any[]): void {
      throw new Error('Method not implemented.');
  }
  verbose(...args: any[]): void {
      throw new Error('Method not implemented.');
  }
}

But it gives

Type 'SuperLogger' provides no match for the signature '(...args: any[]): void'

How do I implement the nameless function? There are some other SO answers about extending the interface, but not seeing any on a class implementing the interface.

CodePudding user response:

How do I implement the nameless function?

If you're referring to the (...args: any[]): void; part of the type, that means that Logger needs to be a function. So for example:

const example: Logger = (...args: any[]) => {};
example.error = /*...*/
example.warn = /*...*/
example.info = /*...*/
example.verbose = /*...*/
  • Related