模块声明与全局类型增强
TypeScript模块声明与全局类型增强:declare module、全局类型扩展。
1. 声明文件基础
1.1 .d.ts 文件
声明文件描述 JavaScript 代码的类型信息,不包含实现:
// utils.d.ts
declare function formatDate(date: Date, format: string): string;
declare const VERSION: string;
declare class EventEmitter {
on(event: string, listener: Function): void;
emit(event: string, ...args: any[]): void;
}
1.2 三斜线指令
/// <reference path="types.d.ts" />
/// <reference types="node" />
/// <reference lib="es2020" />
2. declare module
2.1 为无类型的模块添加类型
// types/legacy-lib.d.ts
declare module 'legacy-lib' {
export function init(config: { apiKey: string }): void;
export function getData(id: string): Promise<{ name: string; value: number }>;
export const version: string;
export default class Client {
constructor(options: { baseUrl: string });
request(path: string): Promise<any>;
}
}
2.2 扩展现有模块
// 扩展 Express 的 Request 类型
declare module 'express' {
interface Request {
userId?: string;
sessionId?: string;
}
}
2.3 扩展 Vue 组件类型
declare module 'vue' {
interface ComponentCustomProperties {
$api: typeof import('./api').default;
$format: typeof import('./utils/format');
}
}
3. 全局类型增强
3.1 扩展全局对象
// global.d.ts
declare global {
interface Window {
__APP_CONFIG__: {
apiBaseUrl: string;
version: string;
};
}
interface Array<T> {
last(): T | undefined;
first(): T | undefined;
}
}
export {}; // 确保文件被视为模块
3.2 全局变量声明
declare var __DEV__: boolean;
declare const __APP_VERSION__: string;
declare function ga(command: string, ...args: any[]): void;
4. 类型声明发布
4.1 @types 包
# 安装社区类型声明
npm install @types/lodash
npm install @types/node
4.2 自带类型声明
// package.json
{
"name": "my-lib",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
}
}
}
5. tsconfig 配置
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types", "./src/types"],
"types": ["node", "jest"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*", "src/**/*.d.ts"]
}