TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

module problem

Open DanielRosenwasser opened this issue 7 years ago • 2 comments

From @penglinjiang on December 28, 2017 6:47

TypeScript Version: 2.6.2 When i study the document about "modules" in "https://www.typescriptlang.org/docs/handbook/modules.html" in chapter "Optional Module Loading and Other Advanced Loading Scenarios",i found that the example in the document could not be executed correctly though grammar of the example is right. my node version is :8.9.3

Code

Validation.ts

export interface StringValidator {
    isAcceptable(s: string): boolean;
}

ZipCodeValidator.ts

import { StringValidator } from "./Validation";

const numberRegexp = /^[0-9]+$/;

export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}

Dynamic Module Loading in Node.js

declare function require(moduleName: string): any;

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

if (needZipValidation) {
    let ZipCodeValidator: typeof Zip = require("./ZipCodeValidator");
    let validator = new ZipCodeValidator();
    if (validator.isAcceptable("...")) { /* ... */ }
}

Expected behavior: it should be executed correctly or the usage of "let validator = new ZipCodeValidator();" in the example is not correct

Actual behavior:

TypeError: ZipCodeValidator is not a constructor
    at Object.<anonymous> (e:\Project\tsc_learn\app.ts:9:21)
    at Module._compile (module.js:632:14)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Copied from original issue: Microsoft/TypeScript#20914

DanielRosenwasser avatar Dec 28 '17 09:12 DanielRosenwasser

From @SalathielGenese on December 28, 2017 8:7

The docs should be updated to :

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

Please @penglinjiang, consider using the below syntax as recommended in this template at least for color to improve readability :

```ts
.write('TypeScript').code;
```

Thanks!

DanielRosenwasser avatar Dec 28 '17 09:12 DanielRosenwasser

We should probably change this to use ECMAScript's new dynamic import syntax.

DanielRosenwasser avatar Dec 28 '17 09:12 DanielRosenwasser