0Pricing
TypeScript Academy · 课时

.d.ts 基础;export type 与 export

学习声明文件基础:环境声明与模块声明、export type 与 export,以及如何为使用者提供正确的 DX。

.d.ts 基础;export type 与 export 是 CoddyKit 上的免费 TypeScript Academy 课时。 这是第 1 节课,共 2 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 TypeScript Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 TypeScript Academy 课程共包含 2 节课。

简介

目标:编写实用的 .d.ts 文件。您将学习环境声明与模块声明、如何声明导出,以及何时使用 export type 与 export。

  • 环境上下文与模块上下文
  • 仅类型导出与值导出
  • 良好实践

环境声明

使用 declare global 扩展全局作用域。添加 export {} 将文件标记为模块,避免冲突。

// globals.d.ts
// Ambient declaration: no import/export, augments global scope
declare global {
  interface Window {
    APP_VERSION: string
  }
}

export {} // ensures this file is a module

模块声明

declare module 描述外部包的结构。在其中使用导出项,以映射 JS 提供的内容。

// types/index.d.ts
// Declare a module with exports
declare module "mylib" {
  export function greet(name: string): string
  export const version: string
}

export type 与 export

export type(或接口)用于仅类型的构造。函数、常量、类等在运行时存在的内容应使用 export。

// shapes.d.ts
export type Point = { x: number; y: number }

export interface User {
  id: string
  name: string
}

export function distance(a: Point, b: Point): number
export const VERSION: string

扩展模块

您可以在另一个声明文件中重新打开现有模块,从而扩展这些模块。这对于修补第三方包很有用。

// augment.d.ts
import "mylib"
declare module "mylib" {
  export function extra(): void
}

最佳实践

最佳实践:

  • 保持 .d.ts 简洁,避免不必要的全局声明。
  • 清晰地区分仅类型导出和值导出。
  • 使用 tsc --noEmit 和示例用法测试声明文件。

export type 检查

快速检查:何时应该使用 export type?

回顾

回顾:.d.ts 文件声明类型而不包含实现。使用 declare global 或 declare module,区分 export type 与 export,并遵循最佳实践。

常见问题解答

「.d.ts 基础;export type 与 export」课时是免费的吗?

是的 — 「.d.ts 基础;export type 与 export」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 TypeScript Academy 课程的其余内容,请升级到 CoddyKit PRO。 TypeScript Academy 课程共包含 2 节课。

「.d.ts 基础;export type 与 export」这节课中我会学到什么?

学习声明文件基础:环境声明与模块声明、export type 与 export,以及如何为使用者提供正确的 DX。 你通过在浏览器中直接运行的动手代码来练习 TypeScript Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 TypeScript Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 TypeScript Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 2 节。

「.d.ts 基础;export type 与 export」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 TypeScript Academy 课中编写并运行代码吗?

能。每节 TypeScript Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. .d.ts 基础;export type 与 export
  2. 发布带类型的包
← 返回 TypeScript Academy