1. 模块声明文件 (d.ts)
// my-module.d.ts
// 声明模块
declare module "my-module" {
export interface Config {
name: string;
version: number;
}
export class MyClass {
constructor(config: Config);
getName(): string;
static create(): MyClass;
}
export function helper(value: string): number;
// 声明全局变量
export const VERSION: string;
}
2. 全局变量声明
// global.d.ts
declare global {
// 全局变量
var myGlobalVar: string;
// 全局函数
function myGlobalFunc(): void;
// 扩展 Window 接口
interface Window {
myCustomProperty: {
version: string;
init(): void;
};
}
// 扩展 Document 接口
interface Document {
customMethod(param: string): boolean;
}
// 扩展 Console 接口
interface Console {
customLog(message: string, level: 'info' | 'warn' | 'error'): void;
}
}
// 使文件成为模块
export {};
3. 第三方库类型补全
// vue-extensions.d.ts
import Vue from 'vue';
// 扩展 Vue 实例
declare module 'vue/types/vue' {
interface Vue {
$myPlugin: {
showToast(message: string): void;
};
$formatDate(date: Date): string;
}
}
// 扩展 Vue 构造函数
declare module 'vue/types/options' {
interface ComponentOptions<V extends Vue> {
myOption?: string;
customValidator?(value: any): boolean;
}
}
4. 命名空间声明
// geometry.d.ts
declare namespace Geometry {
export interface Point {
x: number;
y: number;
}
export interface Circle {
center: Point;
radius: number;
}
export function distance(p1: Point, p2: Point): number;
export function area(circle: Circle): number;
}
// 使用命名空间扩展
declare namespace Geometry {
export interface Rectangle {
topLeft: Point;
width: number;
height: number;
}
export function isPointInRect(point: Point, rect: Rectangle): boolean;
}
5. 混合声明示例
// types.d.ts
// 类型别名
type StringOrNumber = string | number;
type Callback<T> = (data: T) => void;
// 接口
interface User {
id: number;
name: string;
email?: string; // 可选属性
readonly createdAt: Date; // 只读属性
}
// 泛型接口
interface ApiResponse<T = any> {
data: T;
success: boolean;
message?: string;
}
// 函数重载声明
declare function processInput(input: string): string;
declare function processInput(input: number): number;
declare function processInput(input: string | number): string | number;
// 类声明
declare class Calculator {
private value: number;
constructor(initialValue?: number);
add(x: number): this;
subtract(x: number): this;
getValue(): number;
static create(): Calculator;
}
// 枚举
declare enum Status {
Pending = "pending",
Active = "active",
Inactive = "inactive"
}
// 常量枚举(编译时内联)
declare const enum Direction {
Up = 1,
Down,
Left,
Right
}
6. JSON 模块声明
// json-modules.d.ts
declare module "*.json" {
const value: any;
export default value;
}
declare module "*.yaml" {
const value: any;
export default value;
}
declare module "*.css" {
const content: { [className: string]: string };
export default content;
}
7. 条件类型和高级类型
// advanced-types.d.ts
// 映射类型
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};
// 条件类型
type NonNullable<T> = T extends null | undefined ? never : T;
type Extract<T, U> = T extends U ? T : never;
type Exclude<T, U> = T extends U ? never : T;
// 模板字面量类型
type EventName<T extends string> = `${T}Changed`;
type MouseEvent = EventName<'mouse'>; // "mouseChanged"
// 实用工具类型示例
declare type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
declare type Nullable<T> = T | null | undefined;
8. 实际项目示例
// api-client.d.ts
declare module '@company/api-client' {
// 请求配置
export interface RequestOptions {
baseURL?: string;
timeout?: number;
headers?: Record<string, string>;
}
// 响应类型
export interface Response<T = any> {
data: T;
status: number;
statusText: string;
headers: Record<string, string>;
}
// API 客户端类
export class ApiClient {
constructor(options?: RequestOptions);
get<T = any>(url: string, config?: RequestOptions): Promise<Response<T>>;
post<T = any>(url: string, data?: any, config?: RequestOptions): Promise<Response<T>>;
put<T = any>(url: string, data?: any, config?: RequestOptions): Promise<Response<T>>;
delete<T = any>(url: string, config?: RequestOptions): Promise<Response<T>>;
setHeader(name: string, value: string): void;
removeHeader(name: string): void;
}
// 创建实例的工厂函数
export function createClient(options?: RequestOptions): ApiClient;
// 默认导出实例
export const defaultClient: ApiClient;
}
9. tsconfig.json 配置
{
"compilerOptions": {
"declaration": true,
"declarationDir": "./dist/types",
"emitDeclarationOnly": false,
"declarationMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
使用建议
组织文件结构:
types/
├── global.d.ts # 全局声明
├── modules/ # 模块声明
│ ├── vue.d.ts
│ └── jquery.d.ts
├── @types/ # 第三方库类型
└── custom/ # 自定义类型
三斜线指令:
/// <reference types="node" />
/// <reference path="./custom.d.ts" />
生成声明文件:
# 编译生成声明文件
tsc --declaration
只生成声明文件
tsc --emitDeclarationOnly
这些示例涵盖了 TypeScript 声明文件的主要使用场景,可以根据具体需求进行调整和扩展。