Search code examples
typescripttypescript-typings.d.tstypescript-declarations

How can I extend Module declarations exported from @types/node?


@types/node doesn't offer types for private properties (prefixed with _) so I'd like to create a .d.ts file that types these properties:

The closest I have gotten is creating a module.d.ts like this:

declare namespace NodeJS {
    interface Module {
        _compile(code: string, filename: string): string;
    }
}

declare module 'module' {   
    const _extensions: NodeJS.RequireExtensions;
    export { _extensions };

    export function _resolveFilename(filename: string, module: any): string;
}

However, this conflicts with @types/node/module.d.ts:

@types/node/module.d.ts:109:5 - error TS2309: An export assignment cannot be used in a module with other exported elements.

109     export = Module;
        ~~~~~~~~~~~~~~~~

Solution

  • How about export const _extensions: NodeJS.RequireExtensions?

    Here is the completed code

    // module.d.ts
    import Module from "module";
    declare global {
        namespace NodeJS {
            export interface Module {
                _compile(code: string, filename: string): string;
            }
        }
    }
    declare module 'module' {
        export const _extensions: NodeJS.RequireExtensions
        export function _resolveFilename(filename: string, module: any): string;
    }
    

    Also I have tried your _compile declaration and it seems that it doesn't work without wrapping in global in my end.

    Here is the playground