1. 类

实战笔记:


第十二章讲的是 namespace(命名空间);现代项目里组织代码用的是 ES 模块,也就是下面这套 export / import 语法。import { useEffect, useState } from "react"; 这句就属于这里:从包里按名字取出两个导出值。

// 命名导出:一个文件可以有多个
export const PI = 3.14;
export function add(a: number, b: number): number { return a + b; }
export class User {
  constructor(public name: string) {}
}
export interface Point { x: number; y: number; }   // 类型也能导出
 
// 也可以先定义、后集中导出
const version = "1.0.0";
interface Config { debug: boolean; }
export { version, Config };
export { version as appVersion };   // 重命名导出
 
// 默认导出:一个模块只能有一个
export default class Logger {}
// 或者
export default function main() {}
 
// 只导出类型(编译后不产生任何代码)
export type { Point };
import { PI, add } from "./math";            // 命名导入(花括号,名字必须对得上)
import { add as plus } from "./math";        // 重命名导入
import Logger from "./logger";               // 默认导入(不加花括号,名字随便起)
import Logger, { PI } from "./logger";       // 默认 + 命名 混合
import * as math from "./math";              // 整体导入:math.PI、math.add()
import "./polyfill";                         // 只为执行副作用,不导入任何绑定
import { useState, useEffect } from "react"; // 从 npm 包导入(不带 ./ 的是包名)

TypeScript 专有:类型导入

import type { Point, Config } from "./types";       // 只导入类型,编译后被完全擦除
import { type Point, add } from "./types";          // 内联 type 修饰符,按需标注

动态导入(返回 Promise,常用于按需加载 / 代码分割)

const { default: Logger } = await import("./logger");
const math = await import("./math");
// index.ts 里做“统一出口”很常见
export { add } from "./math";
export { add as plus } from "./math";
export * from "./math";
export * as math from "./math";
export type { Point } from "./types";

Node 老项目用的是 CommonJS,写法不同,不要和 import/export 混在同一个文件里:

// CommonJS
const fs = require("fs");
module.exports = { add };
 
// 在 TypeScript 中使用 CommonJS 模块(配合 "module": "commonjs")
import fs = require("fs");
export = myModule;
  • import / export 必须写在模块顶层,不能放进函数或 if 里(import() 动态导入除外)。
  • import 会被提升,语句写在哪不影响执行顺序,但习惯上统一放文件顶部。
  • 文件里只要有顶层 import 或 export,它就是模块,变量不再污染全局。
  • 路径带扩展名的场合:浏览器原生 ESM、Node 的 "type": "module"(ESM 要求写 ./math.js);被 webpack / Vite 打包时通常可以省略。
  • 相关编译选项:module(输出 commonjs / esnext…)、esModuleInterop(默认导入的兼容处理)、verbatimModuleSyntax(开启后类型必须用 import type)。
  • 默认导出和命名导出可以同时用,但一个模块只能有一个默认导出。

把下面这个文件改写成「既提供命名导出、又提供默认导出」的模块,并在另一个文件里用三种方式导入(命名、默认、整体)。

function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}
 
class Formatter {
  constructor(public locale: string) {}
  format(date: Date): string {
    return formatDate(date);
  }
}

参考答案

// utils/formatter.ts
export function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}
 
export class Formatter {
  constructor(public locale: string) {}
  format(date: Date): string {
    return formatDate(date);
  }
}
 
export default formatDate;   // 默认导出同一个函数
 
// main.ts
import formatDate, { formatDate as named, Formatter } from "./utils/formatter";
import * as formatter from "./utils/formatter";
 
console.log(formatDate(new Date()));
console.log(named(new Date()));
console.log(formatter.formatDate(new Date()));
console.log(new Formatter("zh-CN").format(new Date()));

把 types.ts 中拆成两个文件:types/point.ts 与 types/user.ts,再用 types/index.ts 统一重新导出,使外部可以直接 import { Point, User } from "./types"。

参考答案

// types/point.ts
export interface Point { x: number; y: number; }
 
// types/user.ts
export interface User { id: string; name: string; }
 
// types/index.ts
export type { Point } from "./point";
export type { User } from "./user";

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • typescript.1791533033.txt.gz
  • 最后更改: 2026/10/09 16:03
  • 由 张叶安