李恒道 发表于 2022-9-18 16:36:51

【翻译】解释TypeScript 中的export =语法

# 解释 TypeScript 中的“export =”和“export as namespace”语法含义
原文链接https://stackoverflow.com/questions/44847749/explain-export-and-export-as-namespace-syntax-in-typescript

I am trying to make use of the type declarations files in the DefinitelyTyped repository. Many of these files use the following pattern:
我正在尝试使用DefinitelyTyped库的类型声明文件,许多文件使用了这种模式
```javascript
export = React;
export as namespace React;
```
Googling around, I've found references to this being used to make a declaration file usable in both module-based and non-module-based systems. However, I'm struggling to find a clear explanation of:
通过谷歌,我发现这种引用被用于同时基于文件和非文件模块系统来声明声明,但是,我努力的寻找一个清晰的解释
what each of these lines exactly does individually and
how exactly this combination works to support both types of consumers.
这里的每一行准确描述做了什么以及
究竟如何联合使用去符合类型的代码的使用
The first form is used for CommonJS and AMD module systems. You have to match the export = React with import React = require('./React')
第一种形式用于Commonjs以及AMD模块系统,在export = React的时候,最好使用import React = require('./React')

查看文档下方的例子
https://stackoverflow.com/questions/44847749/explain-export-and-export-as-namespace-syntax-in-typescript

ZipCodeValidator.ts
```javascript
let numberRegexp = /^+$/;
class ZipCodeValidator {
    isAcceptable(s: string) {
      return s.length === 5 && numberRegexp.test(s);
    }
}
export = ZipCodeValidator;
```

Test.ts
```javascript
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:
而export as namespace方式创建了一个全局变量,所以不需要导入也可以进行使用,但是你依然可以使用the import { name } from "some-library"方式来进行导入,查看文档下方给出的例子
https://www.typescriptlang.org/docs/handbook/modules.html#umd-modules

math-lib.d.ts
```javascript
export const isPrime(x: number): boolean;
export as namespace mathLib;
```
The library can then be used as an import within modules:
这个库可以使用import导入
```javascript
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.
现在你拥有一个通用类型库,尽管不知道正在使用哪种模块系统,所以他试图覆盖所有的基础模块类型系统
页: [1]
查看完整版本: 【翻译】解释TypeScript 中的export =语法