Creating an anonymous object that implements an interface with overloaded functions

Viewed 1307

I have a TypeScript interface that has a single function called "send" that is overloaded with two allowed signatures.

export interface ConnectionContext {
    send(data: ConnectionData): void;
    send(data: ConnectionData, timeout: number): Promise<ConnectionData>;
}

I'm trying to create an anonymous object that implements this interface:

const context: ConnectionContext = {
    send: (data: ConnectionData, timeout?: number): void | Promise<ConnectionData> => {
        // 
    }
};

However, TypeScript 2.4.1 is producing the following errors:

Error:(58, 15) TS2322:Type '{ send: (data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>; }' is not assignable to type 'ConnectionContext'.

Types of property 'send' are incompatible.

Type '(data: ConnectionData, timeout?: number | undefined) => void | Promise<ConnectionData>' is not assignable to type '{ (data: ConnectionData): void; (data: ConnectionData, timeout: number): Promise<ConnectionData>; }'.

Type 'void | Promise<ConnectionData>' is not assignable to type 'Promise<ConnectionData>'.

Type 'void' is not assignable to type 'Promise<ConnectionData>'.

I know I can do this with a class but I'd rather not create an entire class if there is some way to do this without one.

1 Answers
Related