🚀 TypeScript中的ambient类型是什么?
欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。
什么是 Ambient 类型?
在 TypeScript 中,ambient(环境声明) 是指仅描述类型信息、不包含实际运行时实现的声明。
核心作用:告诉 TypeScript:"这个东西在运行时已经存在(由外部提供),你只需做类型检查,无需生成对应的 JS 代码"。
📦 常见使用场景
1. 为第三方 JS 库添加类型
declare function $(selector: string): any;
$('#app').show();
说明
declare 关键字表示这是环境声明 - TypeScript 只做类型检查,不会生成任何 JavaScript 代码
- 运行时需要确保 jQuery 已经加载
2. 声明全局变量/模块
声明环境变量
declare const __VERSION__: string;
console.log(__VERSION__);
声明无类型定义的 npm 包
declare module 'some-legacy-lib' {
export function doSomething(): void;
}
📁 声明文件(.d.ts)
Ambient 声明通常放在 .d.ts 文件中,例如:
src/
├── index.ts
└── types/
└── global.d.ts ← 存放 declare 声明
常见的 Ambient 声明类型
1. 声明全局函数
declare function myGlobalFunction(param: string): void;
myGlobalFunction('hello');
2. 声明全局变量
declare const API_URL: string;
declare let isDebug: boolean;
declare var globalConfig: { timeout: number };
console.log(API_URL);
3. 声明全局命名空间
declare namespace MyLib {
function init(): void;
const version: string;
}
MyLib.init();
console.log(MyLib.version);
4. 声明全局类
declare class MyClass {
constructor(name: string);
getName(): string;
}
const instance = new MyClass('test');
instance.getName();
5. 声明模块
declare module '*.css' {
const content: { [className: string]: string };
export default content;
}
declare module '*.png' {
const value: string;
export default value;
}
import styles from './App.module.css';
import logo from './logo.png';
实战示例
示例 1:为 jQuery 添加类型声明
interface JQuery {
show(): JQuery;
hide(): JQuery;
text(content?: string): JQuery | string;
}
declare function $(selector: string): JQuery;
$('#app').show().text('Hello World');
示例 2:声明 Webpack 环境变量
declare const process: {
env: {
NODE_ENV: 'development' | 'production';
API_URL: string;
};
};
if (process.env.NODE_ENV === 'development') {
console.log('开发模式');
}
示例 3:扩展全局 Window 对象
interface Window {
myCustomProperty: string;
myCustomMethod(): void;
}
window.myCustomProperty = 'test';
window.myCustomMethod();
示例 4:声明第三方库模块
declare module 'legacy-lib' {
export interface Config {
timeout: number;
retries: number;
}
export function init(config: Config): void;
export function request(url: string): Promise<any>;
}
import { init, request } from 'legacy-lib';
init({ timeout: 5000, retries: 3 });
request('/api/data');
Ambient 声明 vs 普通声明
| 特性 | Ambient 声明(declare) | 普通声明 |
| 关键字 | declare | 无 declare |
| 生成 JS 代码 | ❌ 不生成 | ✅ 生成 |
| 包含实现 | ❌ 仅类型 | ✅ 包含实现 |
| 文件类型 | 通常在 .d.ts 文件 | .ts 或 .tsx 文件 |
| 用途 | 描述外部已存在的代码 | 定义和实现新代码 |
配置 tsconfig.json
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types", "./types"],
"types": ["node", "jest"]
},
"include": ["src/**/*", "types/**/*"]
}
配置说明
typeRoots:指定类型声明文件的查找目录 types:指定要包含的类型包 include:包含 types 目录中的 .d.ts 文件
最佳实践
✅ 推荐做法
- 将 ambient 声明放在
types/ 或 @types/ 目录 - 使用
.d.ts 文件扩展名 - 为第三方库优先使用
@types/xxx 包 - 自定义声明文件命名清晰(如
global.d.ts、window.d.ts) - 避免在
.d.ts 文件中使用 import/export(除非声明模块)
核心要点总结
💡 关键知识点
- Ambient 声明:使用
declare 关键字,仅描述类型,不生成 JS 代码 - 主要用途:为外部 JS 库、全局变量、环境变量添加类型
- 文件位置:通常放在
.d.ts 文件中 - 声明类型:函数、变量、类、命名空间、模块
- 配置要求:在
tsconfig.json 中正确配置 typeRoots 和 include