Skip to content

Request: import module types without calling import x = require('x') #1478

@jt000

Description

@jt000

I am investigating how to mock node.js dependencies and it has stemmed to a couple issues.

  1. Cannot call var http = require('http') and have compile time support of http (it will always be "any")
  2. Cannot call import http = require('http') anytime except in the top-most level of a module.

What I would like to do is get compile time support of a module without calling require. For example, maybe something like the below code...

import http = /* typeLoad('http') - get type information without creating any code in JS for compile time support */;
export class Webhost {
    start(): http.Server {
        /* actually get the require definition for 'http' here */
        var httpDef: /* module 'http' */ = require('http');
        return httpDef.createServer();
    }
}

This would allow me to have some compiler support for types and functions, but would allow me to delay actually getting the object in order to allow me to mock it in tests. This could also be used to create dependency injection methods like:

// web.ts
export class Webhost {
    httpDef: /* module 'http' */
    constructor(httpDef: /* module 'http' */ = require('http') /* default to require */) {
        this.httpDef = httpDef;
    }

    start(): http.Server {
        return this.httpDef.createServer();
    }
}

// test.ts
var mockHttpServer: /* module 'http' */ = {
    createServer: () => console.log('server created');
};

import web = require('./web');
var webHost = new web.Webhost(mockHttpServer);

Note: This might be specific to how node.d.ts is implemented since the modules are declared with declare module "http" {...}

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions