TS文档学习 --- module

151 阅读2分钟

本篇翻译整理自 TypeScript Handbook 中 「Module」 章节。

在 TypeScript 中,就像在 ECMAScript 2015 中 ,任何包含了一个顶层 import 或者 export 的文件会被认为是一个模块。

相对应的,一个没有顶层导入和导出声明的文件会被认为是一个脚本,它的内容会在全局范围内可用。

模块会在它自己的作用域,而不是在全局作用域里执行。这意味着,在一个模块中声明的变量、函数、类等,对于模块之外的代码都是不可见的,除非你显示的导出这些值。

相对应的,要消费一个从另一个的模块导出的值、函数、类、接口等,也需要使用导入的格式先被导入

TS中的模块

在一个脚本文件(普通的TypeScript文件)中,变量和类型会被声明在共享的全局作用域,它会被假定你或者使用 outFile 编译选项,将多个输入文件合并成一个输出文件,或者在 HTML使用多个 <script> 标签加载这些文件。

如果你有一个文件,现在没有任何 import 或者 export,但是你希望它被作为模块处理,添加这行代码:

export {};
复制代码

这会把文件改成一个没有导出任何内容的模块,这个语法可以生效,无论你的模块目标是什么。

在TypeScript中,类型可以像 JavaScript 值那样,使用相同的语法被导出和导入:

// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
 
export interface Dog {
  breeds: string[];
  yearOfBirth: number;
}
 
// @filename: app.ts
import { Cat, Dog } from "./animal.js";
type Animals = Cat | Dog;

导入类型

// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export type Dog = { breeds: string[]; yearOfBirth: number };
export const createCatName = () => "fluffy";
 
// @filename: valid.ts
import type { Cat, Dog } from "./animal.js";
export type Animals = Cat | Dog;
 
// @filename: app.ts
// 在导入createCatName函数的前面加上关键字type
// 表示引入的是createCatName函数的类型信息
import type { createCatName } from "./animal.js";
const name = createCatName(); // error --- createCatName是类型信息不是函数,不可以被调用

内置类型导入

TypeScript 4.5 也允许单独的导入,你需要使用 type 前缀 ,表明被导入的是一个类型

这些可以让一个非 TypeScript 编译器比如 Babel 或者 esbuild 知道什么样的导入可以被安全移除

// @filename: app.ts
import { createCatName, type Cat, type Dog } from "./animal.js";
 
export type Animals = Cat | Dog;
const name = createCatName();