做婚恋网站,庄浪县县住房建设局网站,重庆seo网站设计,内蒙古众信国际旅行社电话TypeScript 中的声明文件#xff08;Declaration Files#xff09;详解
声明文件#xff08;Declaration Files#xff09; 是 TypeScript 的核心机制之一#xff0c;用于为非 TypeScript 编写的代码#xff08;如纯 JavaScript 文件、第三方库、浏览器 API、全局变量等…TypeScript 中的声明文件Declaration Files详解声明文件Declaration Files是 TypeScript 的核心机制之一用于为非 TypeScript 编写的代码如纯 JavaScript 文件、第三方库、浏览器 API、全局变量等提供类型信息。声明文件以.d.ts为后缀只包含类型定义不包含实现代码编译后不会生成 JavaScript。1. 为什么需要声明文件JavaScript 库如 jQuery、Lodash没有类型信息。浏览器内置 API如document、window、fetch是全局的。项目中混用.js文件。第三方 npm 包没有内置类型定义。使用声明文件后TypeScript 能在使用这些代码时提供智能提示、类型检查和错误提示。2. 基本语法与结构声明文件的核心关键字declare声明变量、函数、类、模块等存在不实现。module/namespace组织全局或模块声明。interface/type定义类型。export/import模块化声明。3. 常见声明类型a. 全局变量/函数声明// globals.d.tsdeclarevarmyGlobalVar:string;// 全局变量declarefunctionmyGlobalFunction(msg:string):void;declareclassGlobalClass{constructor(name:string);say():void;}declareconstBUILD_VERSION:string;// 全局常量使用myGlobalFunction(hello);// 有类型提示b. 全局命名空间声明扩展现有对象// augmentations.d.tsdeclareglobal{interfaceWindow{myAppConfig:{apiUrl:string;debug:boolean;};}namespaceNodeJS{interfaceProcessEnv{NODE_ENV:development|production;API_KEY:string;}}}// 使用window.myAppConfig.apiUrl;// 有提示process.env.API_KEY;// 类型安全c. 模块声明为 JS 模块提供类型// declarations/lodash.d.tsdeclaremodulelodash{exportfunctionchunkT(array:T[],size?:number):T[][];exportfunctiondebounceTextendsFunction(func:T,wait:number):T;// ... 其他函数exportdefault_;// 默认导出如果库是 defaultconst_:any;}// 使用import_fromlodash;_.chunk([1,2,3,4],2);// 有类型提示d. 为现有模块添加类型Module Augmentation扩展第三方库如 express// types/express.d.tsimportexpress;declaremoduleexpress-serve-static-core{interfaceRequest{user?:{id:number;name:string;};}}// 使用 express 时app.use((req,res,next){req.user?.name.toUpperCase();// 有提示不报错});4. DefinitelyTyped —— 社区类型定义最常用的声明文件来源types 组织安装npminstall--save-dev types/lodashnpminstall--save-dev types/jquerynpminstall--save-dev types/node# Node.js 全局类型npminstall--save-dev types/react超过 10,000 个流行库的类型定义。优先使用types/xxx避免自己写。5. 创建自己的声明文件示例为一个 JS 文件提供类型项目结构src/ utils.js // 纯 JavaScript utils.d.ts // 类型声明// utils.jsmodule.exports{formatDate(date){returndate.toISOString();},capitalize(str){returnstr.charAt(0).toUpperCase()str.slice(1);}};// utils.d.tsexportfunctionformatDate(date:Date):string;exportfunctioncapitalize(str:string):string;使用import*asutilsfrom./utils;utils.capitalize(hello);// 有类型提示示例为第三方无类型库写声明// declarations/my-lib.d.tsdeclaremodulemy-lib{exportinterfaceOptions{timeout?:number;retries?:number;}exportfunctionrequest(url:string,options?:Options):Promisestring;exportdefaultrequest;}放在项目中任意位置TS 会自动识别。6. tsconfig.json 中的声明文件配置{compilerOptions:{typeRoots:[./node_modules/types,./types],// 自定义类型目录types:[node,lodash]// 只加载指定 types},include:[src/**/*.ts,src/**/*.d.ts,// 包含自定义声明文件types/**/*.d.ts]}7. 最佳实践建议建议说明优先使用types/xxx社区维护质量高自定义声明放types/或项目根便于管理全局增强用declare global扩展 Window、process 等模块声明用declare module xxx为 JS 库提供类型避免重复声明利用模块增强而非重写声明文件不包含实现代码只写类型编译后消失开启skipLibCheck: true加速编译可选小结声明文件类型速查场景写法示例全局变量declare var $: any;扩展 Windowdeclare global { interface Window { app: any; } }为 JS 模块declare module my-lib { export function fn(): void; }第三方库npm install types/lodashNode.js 全局types/node模块增强declare module express { interface Request { user?: User; } }声明文件是 TypeScript 与 JavaScript 生态无缝衔接的桥梁。掌握它后你可以安全地使用任何 JS 库同时享受完整的类型支持。如果您想看具体示例如为 jQuery、Axios、或自定义 JS 项目写声明文件或者如何发布自己的types包请告诉我