Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

content about ts export/import #2

Open
JoyMoch opened this issue Sep 15, 2020 · 1 comment
Open

content about ts export/import #2

JoyMoch opened this issue Sep 15, 2020 · 1 comment

Comments

@JoyMoch
Copy link
Owner

JoyMoch commented Sep 15, 2020

microsoft/TypeScript#7185

@JoyMoch
Copy link
Owner Author

JoyMoch commented Sep 15, 2020

Explain “export =” and “export as namespace” syntax in TypeScript origin website

The first form is used for CommonJS and AMD module systems. You have to match the export = React with import React = require('./React')

See the documentation which gives this example:

ZipCodeValidator.ts

let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}
export = ZipCodeValidator;

Test.ts

import zip = require("./ZipCodeValidator");

// Some samples to try
let strings = ["Hello", "98052", "101"];

// Validators to use
let validator = new zip();

// Show whether each string passed each validator
strings.forEach(s => {
  console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
});

The export as namespace form creates a global variable so it can be used without importing, but you may still import it with the import { name } from "some-library" form of import. See the documentation which gives this example:

math-lib.d.ts

export const isPrime(x: number): boolean;
export as namespace mathLib;

The library can then be used as an import within modules:

import { isPrime } from "math-lib";
isPrime(2);
mathLib.isPrime(2); // ERROR: can't use the global definition from inside a module

It can also be used as a global variable, but only inside of a script. (A script is a file with no imports or exports.)

mathLib.isPrime(2);

Here you have a generic type library which doesn't know which module system is being used so it tries to cover all bases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant