Explain the syntax for "export =" and "export as namespace" in TypeScript
I'm trying to use type declaration files in the DefinitelyTyped repository. Many of these files use the following pattern:
export = React;
export as namespace React;
Google, I found links to this to use a declaration file that can be used in both modular and non-modular systems. However, I am struggling to find a clear explanation of (a) what each of these lines does individually, and (b) exactly how this combination works to support both types of consumers.
source to share
The first form is used for CommonJS and AMD systems. You must match export = React
withimport React = require('./React')
See the documentation for the following 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 form export as namespace
creates a global variable, so it can be used without import, but you can still import it with the import form import { name } from "some-library"
. See the documentation which gives the following example:
Math-lib.d.ts
export const isPrime(x: number): boolean;
export as namespace mathLib;
The library can then be used as an import inside 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 a script. (A script is a file with no import or export.)
mathLib.isPrime(2);
Here you have a generic type library that doesn't know which module system is in use, so it tries to cover all bases.
source to share