Skip to content

Cannot augment WebSocket interface in TypeScript #1877

@zimtsui

Description

@zimtsui

when adding a method sendAsync to WebSocket, i have to augment the interface of WebSocket

// promisify.ts
export function promisifySend(socket: WebSocket): void {
    socket.sendAsync = function (/*......*/): Promise<void> {
        /*......*/
    }
}
declare module 'ws' {
    export default interface Websocket { // default export
        sendAsync(/*......*/): Promise<void>;
    }
}

//1.ts
import WebSocket from 'ws'; // import a default export
import { promisifySend } from './promisify.ts';

but this syntax above is illegal in TS, see microsoft/TypeScript#14080

TS only allows to augment a interface which is a named export, for example

// promisify.ts
export function promisifySend(socket: WebSocket): void {
    socket.sendAsync = function (/*......*/): Promise<void> {
        /*......*/
    }
}
declare module 'ws' {
    export interface Websocket { // named export
        sendAsync(/*......*/): Promise<void>;
    }
}

// 1.ts
import { WebSocket } from 'ws'; // import a named export
import { promisifySend } from './promisify.ts';

this requires WebSocket is not default export but a named export.

obviously, this is a bug of TS, not of ws. but you cannot look forward to TS fixing its bug. so i recommend ws exports a WebSocket within WebSocket, like

// index.js
const WebSocket = require('./lib/websocket');
WebSocket.WebSocket = WebSocket;
module.exports = WebSocket;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions