Nicolas S.Xu Nicolas S.Xu - 5 months ago 26
TypeScript Question

what is the correct way to import a module in Typescript?

I am a bit confused when reading official document about Typescript module.

declare function require(moduleName: string): any;
// why declare require?
import { ZipCodeValidator as Zip } from "./ZipCodeValidator";
// Zip is being imported here, right?
if (needZipValidation) {
let ZipCodeValidator: typeof Zip = require("./ZipCodeValidator");
// Zip is already imported before if statement, why import again?
let validator = new ZipCodeValidator();
if (validator.isAcceptable("...")) { /* ... */ }


import { ZipCodeValidator as Zip } from "./ZipCodeValidator";

After this above line of code, ZipCodeValidator is already loaded, and available as Zip in the module of current file. Why later in the if condition load it again at the following line of code?

let ZipCodeValidator: typeof Zip = require("./ZipCodeValidator");

Noted: They load the same module using different method, one is import, the other is require. Why using different way?


Why do you need to declare require function signature? What does declare do? If declared, where is the implementation?


The example you are showing is to implement a particular way of importing a module. This shows how to conditionally import a module. This is a special case that I would think you will not need to do all the time.

So, to answer your questions specifically,

  1. After you do this: import { ZipCodeValidator as Zip } from "./ZipCodeValidator"; The TS compiler is smart enough to know that if Zip is only used in a type position, then it shouldn't load the module. The second require statement is where the actual importing occurs.

  2. The declare statement is needed to ensure that TS knows about the special require keyword. You should not need to do this explicitly if you are using a typings library for node.js.