Typescript: Declare variable as typeof external module without import

Created on 8 Sep 2015  路  3Comments  路  Source: microsoft/TypeScript

Hey there,

Is it possible to write an external (commonjs) module "A", then in another module "B"'s code, declare a variable as being typeof module "A" without using import which ends up require-ing module "A".

The reason I want to do this is that I will be passing a reference to module "A" to the constructor of a class in another module "B", because I want module "A" to be a singleton. But I want to type the argument in the constructor to that of module "A", as if module "A" had been imported using import A = require("A");

The reason I want a singleton module is that this module might contain instances of classes that manage database connections, etc, and I don't really want them re-initialising each time I have to import; I want to be able to pass them around rather than rely on potential "node-module cache" magic.

Is there a way to do this? I've thought of other ways I can achieve want I want but this feels like the simplest, if it's possible.

Question

Most helpful comment

Module imports are elided if they are not used in a value position. so if your import of module A is only used in a type position the require call will not be written out.

for instance:

// B.ts
import s = require("./A");
var x: typeof s;

emits

var x;

does this answer your question?

All 3 comments

Module imports are elided if they are not used in a value position. so if your import of module A is only used in a type position the require call will not be written out.

for instance:

// B.ts
import s = require("./A");
var x: typeof s;

emits

var x;

does this answer your question?

Oh, that's great! It definitely answers my question. I couldn't find this in the documentation, so thanks a tonne for your help. :)

Hi Folks,
I have a question which is on the same lines. I tried above solution but it did now work for me.
I am importing classes from a webpack module parent import { A, B } from "parent";
I simply want to call constructor for these classes. I tried const a = A( { data: 1} ); This does not give any TS error on compile. But it breaks on runtime javascript saying , Type error A is not a constructor.

Do I need to create custom types and add it in devDependancies ? Or is there a specific way to export my "parent" module like export default.

Any help is appreciated.

Cheers,
Sudeep

Was this page helpful?
0 / 5 - 0 ratings