1. 声明文件:TypeScript与JavaScript生态的桥梁
作为一名长期使用TypeScript的前端开发者,我深刻体会到.d.ts声明文件在项目中的重要性。当你在Ubuntu或Linux环境下开发时,经常会遇到需要集成第三方JavaScript库的情况。这些库往往没有内置类型支持,而声明文件正是解决这一痛点的完美方案。
声明文件的核心价值在于:
- 为纯JavaScript代码提供静态类型检查
- 在VS Code等IDE中实现智能代码补全
- 在编译阶段捕获潜在的类型错误
- 保持TypeScript项目与庞大JavaScript生态的兼容性
在实际运维工作中,我们经常需要快速集成各种工具库。有了声明文件,即使面对无类型的JS库,也能获得与原生TypeScript代码相同的开发体验。这大大提升了开发效率和代码质量。
2. 声明文件基础:从创建到使用
2.1 创建你的第一个.d.ts文件
在Ubuntu/Linux环境下创建声明文件非常简单:
bash复制touch my-module.d.ts
一个基本的声明文件内容如下:
typescript复制// 声明全局变量
declare const VERSION: string;
// 声明函数
declare function calculateArea(radius: number): number;
// 声明接口
declare interface User {
id: number;
name: string;
}
注意:声明文件只包含类型信息,不包含任何实际实现代码。这是.d.ts文件与普通.ts文件的关键区别。
2.2 声明文件的三种使用方式
- 三斜线指令引用(适合旧项目)
typescript复制/// <reference path="./my-module.d.ts" />
- 通过tsconfig.json自动包含(推荐方式)
json复制{
"include": ["**/*.d.ts"]
}
- 模块声明方式(为第三方库添加类型)
typescript复制declare module "some-js-lib" {
export function doSomething(): void;
}
在Linux环境下开发时,我习惯将项目所有的声明文件统一放在types/目录下,然后在tsconfig.json中配置:
json复制{
"typeRoots": ["./node_modules/@types", "./types"]
}
3. 深入声明文件编写技巧
3.1 为复杂JavaScript库添加类型支持
假设我们需要为以下JavaScript工具函数添加类型:
javascript复制// utils.js
export function formatDate(date, format = 'YYYY-MM-DD') {
// 实现省略
}
export const DEFAULT_TIMEOUT = 3000;
对应的声明文件可以这样写:
typescript复制// utils.d.ts
declare module "utils" {
export function formatDate(
date: Date | string | number,
format?: string
): string;
export const DEFAULT_TIMEOUT: number;
}
3.2 处理类与命名空间
对于面向对象的JS代码,声明文件需要准确描述类结构:
typescript复制declare class ImageLoader {
constructor(config?: { maxParallel?: number });
load(url: string): Promise<HTMLImageElement>;
abort(url: string): void;
static createDefaultLoader(): ImageLoader;
}
declare namespace ImageProcessing {
function resize(img: HTMLImageElement, options: { width: number }): HTMLCanvasElement;
function applyFilter(img: HTMLImageElement, filterName: string): HTMLCanvasElement;
}
3.3 高级类型技巧
- 条件类型声明:
typescript复制declare type MaybeArray<T> = T | T[];
- 映射类型声明:
typescript复制declare type ReadonlyRecord<K extends string | number | symbol, V> = {
readonly [P in K]: V;
};
- 函数重载声明:
typescript复制declare function parse(input: string): number;
declare function parse(input: string, radix: number): number;
declare function parse(input: string, options: { asFloat: boolean }): number;
4. 为第三方库添加类型支持的实战
4.1 使用DefinitelyTyped社区类型
对于流行的JavaScript库,通常已经有社区维护的类型定义:
bash复制# 在Ubuntu/Linux下安装lodash的类型定义
npm install --save-dev @types/lodash
4.2 自定义第三方库声明
当遇到没有类型定义的库时,我们可以自己创建:
typescript复制// types/legacy-chart.d.ts
declare module "legacy-chart" {
interface ChartOptions {
width?: number;
height?: number;
data: Array<{ x: number; y: number }>;
}
export function createChart(container: HTMLElement, options: ChartOptions): void;
export function updateChart(id: string, data: Array<{ x: number; y: number }>): void;
}
4.3 模块扩展技巧
有时我们需要扩展已有类型定义的模块:
typescript复制// types/extensions.d.ts
import "vue";
declare module "vue" {
interface ComponentCustomProperties {
$formatCurrency: (value: number) => string;
}
}
5. 声明文件的最佳实践与陷阱
5.1 最佳实践
- 保持声明与实现同步:当JavaScript代码变更时,及时更新声明文件
- 使用JSDoc增强提示:
typescript复制declare interface User {
/**
* 用户唯一标识符
* @example
* const userId = user.id;
*/
id: number;
}
- 版本控制:声明文件应与库版本保持一致
5.2 常见陷阱
- 过度声明:避免声明不存在的API,这会导致虚假的类型安全
- 忽略可选属性:仔细检查文档,确保所有可选属性都标记为
? - 版本不匹配:确保声明文件版本与使用的库版本兼容
5.3 性能考量
在大型Linux服务器项目中,声明文件的组织方式会影响编译性能:
- 将不常变动的声明文件单独存放
- 避免在声明文件中使用复杂的条件类型
- 使用
import type减少运行时影响
6. 声明文件在复杂项目中的应用
6.1 Monorepo项目中的声明文件管理
在Monorepo架构下,声明文件的共享需要特别注意:
bash复制monorepo/
├── packages/
│ ├── lib-a/ # 包含自己的声明文件
│ ├── lib-b/ # 依赖lib-a的类型
│ └── types/ # 共享类型定义
└── tsconfig.base.json
在tsconfig.base.json中配置:
json复制{
"compilerOptions": {
"paths": {
"@lib-a/*": ["packages/lib-a/src/*"],
"@types/*": ["packages/types/*"]
}
}
}
6.2 渐进式TypeScript迁移策略
对于正在从JavaScript迁移到TypeScript的Linux运维工具:
- 首先为关键模块添加声明文件
- 逐步将.js文件重命名为.ts
- 使用
allowJs和checkJs选项进行渐进式验证
6.3 环境变量声明
为Node.js环境变量添加类型安全:
typescript复制// types/env.d.ts
declare namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'development' | 'production' | 'test';
API_URL: string;
PORT?: string;
}
}
7. 调试与验证声明文件
7.1 测试声明文件的正确性
创建测试文件验证声明是否准确:
typescript复制// tests/type-tests.ts
import * as lib from 'my-lib';
// 测试函数签名
const result = lib.calculate(42);
result.toFixed(); // 应该能提示number的方法
// 测试接口
const user: lib.User = {
id: 1,
name: 'Test'
};
7.2 使用tsd工具进行类型测试
安装tsd进行声明文件的单元测试:
bash复制npm install --save-dev tsd
创建测试文件:
typescript复制// test-d/my-lib.test-d.ts
import { expectType } from 'tsd';
import * as lib from '../dist';
expectType<(a: number, b: number) => number>(lib.add);
expectType<number>(lib.DEFAULT_TIMEOUT);
7.3 常见错误排查
-
"无法找到模块"错误:
- 检查
typeRoots配置 - 确保文件扩展名正确
- 检查
-
类型不匹配警告:
- 检查声明是否与实现一致
- 确认库的准确版本
-
全局类型污染:
- 避免在模块声明文件中使用全局声明
- 使用
export {}确保文件被视为模块
8. 高级技巧与性能优化
8.1 声明合并技巧
利用TypeScript的声明合并特性增强已有类型:
typescript复制// 扩展Express的Request类型
declare global {
namespace Express {
interface Request {
user?: {
id: string;
name: string;
};
}
}
}
8.2 条件类型与模板字面类型
在声明文件中使用高级类型特性:
typescript复制declare type EventMap = {
click: { x: number; y: number };
hover: { element: HTMLElement };
};
declare type EventHandler<T extends keyof EventMap> = (payload: EventMap[T]) => void;
declare function on<T extends keyof EventMap>(
event: T,
handler: EventHandler<T>
): void;
8.3 减少编译开销
优化声明文件组织提升编译速度:
- 避免过大的单体声明文件
- 使用
import type减少依赖 - 将稳定的声明文件与频繁变更的文件分开
在Linux服务器环境下,可以通过以下命令检查声明文件对编译时间的影响:
bash复制time tsc --noEmit --extendedDiagnostics
9. 声明文件与前端框架集成
9.1 React组件类型声明
为React组件库添加类型支持:
typescript复制import * as React from 'react';
declare module 'awesome-react-components' {
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
}
export const Button: React.FC<ButtonProps>;
}
9.2 Vue插件类型增强
为Vue插件添加类型支持:
typescript复制import { PluginFunction } from 'vue';
declare module 'vue-analytics' {
interface EventOptions {
category: string;
action: string;
label?: string;
value?: number;
}
export const install: PluginFunction<{ id: string }>;
}
9.3 通用前端工具类型
为前端工具函数添加类型:
typescript复制declare module 'frontend-utils' {
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number,
immediate?: boolean
): (...args: Parameters<T>) => void;
export function throttle<T extends (...args: any[]) => any>(
func: T,
limit: number
): (...args: Parameters<T>) => ReturnType<T>;
}
10. 声明文件在Node.js后端开发中的应用
10.1 为自定义模块添加类型
为Node.js模块添加类型支持:
typescript复制// types/database.d.ts
declare module 'database' {
import { EventEmitter } from 'events';
interface QueryOptions {
timeout?: number;
retries?: number;
}
export class DatabaseClient extends EventEmitter {
constructor(connectionString: string);
query<T = any>(sql: string, options?: QueryOptions): Promise<T[]>;
close(): Promise<void>;
}
}
10.2 处理CommonJS模块
为CommonJS模块添加类型:
typescript复制declare module 'legacy-module' {
function createInstance(config: object): any;
namespace createInstance {
interface Config {
url: string;
timeout?: number;
}
}
export = createInstance;
}
10.3 环境特定类型
为不同环境配置添加类型:
typescript复制// types/config.d.ts
declare interface AppConfig {
database: {
host: string;
port: number;
username: string;
password: string;
};
redis?: {
url: string;
};
}
declare const config: AppConfig;
export default config;
11. 声明文件的版本管理与发布
11.1 与npm包一起发布类型
在package.json中配置类型入口:
json复制{
"name": "my-package",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts"
}
11.2 独立发布类型定义
为纯JavaScript库单独发布类型定义:
- 创建
@types/my-library包 - 在package.json中指定依赖版本范围
- 遵循DefinitelyTyped的贡献指南
11.3 版本兼容性策略
使用TypeScript的版本标记确保兼容性:
typescript复制// types/versions.d.ts
declare module 'some-library/v2' {
// v2的类型定义
}
declare module 'some-library/v3' {
// v3的类型定义
}
12. 声明文件的未来与替代方案
12.1 JSDoc类型注释的兴起
对于不想完全迁移到TypeScript的项目,可以使用JSDoc提供类型提示:
javascript复制/**
* @typedef {Object} User
* @property {number} id
* @property {string} name
*/
/**
* @param {User} user
* @returns {string}
*/
function formatUserName(user) {
return `User: ${user.name}`;
}
12.2 TypeScript的自动类型生成
使用--declaration选项自动生成.d.ts文件:
bash复制tsc --declaration --emitDeclarationOnly
12.3 类型推断的进步
随着TypeScript类型推断能力的增强,某些情况下不再需要显式声明:
typescript复制// 现代TypeScript可以推断出函数的返回类型
export function add(a: number, b: number) {
return a + b;
}
13. 个人实战经验分享
在多年的TypeScript开发中,我总结了以下宝贵经验:
- 渐进式类型添加:大型项目不要试图一次性添加所有类型,先从核心模块开始
- 类型测试:像测试代码一样测试你的类型定义
- 文档化类型:使用JSDoc为复杂类型添加说明
- 团队约定:建立统一的声明文件编写规范
- 性能监控:定期检查类型检查对构建速度的影响
一个特别有用的技巧是创建types-tests目录,专门存放用于验证类型定义的测试代码。这可以及早发现类型定义中的问题。
14. 常见问题解决方案
14.1 如何处理动态属性对象?
使用索引签名:
typescript复制declare interface DynamicObject {
[key: string]: any;
}
14.2 如何为函数添加自定义属性?
使用交叉类型:
typescript复制declare function foo(): void;
declare namespace foo {
export const version: string;
}
14.3 如何处理全局变量污染?
使用模块声明确保隔离:
typescript复制export {}; // 确保文件被视为模块
declare global {
interface Window {
myGlobal: any;
}
}
15. 工具链推荐
- dtslint:专门用于测试声明文件的工具
- types-publisher:DefinitelyTyped使用的发布工具
- tsd:声明文件单元测试工具
- @microsoft/api-extractor:管理大型项目的类型定义
在Ubuntu/Linux环境下安装:
bash复制npm install -g dtslint tsd
16. 声明文件与构建工具集成
16.1 Webpack集成
配置ts-loader处理声明文件:
javascript复制module.exports = {
module: {
rules: [
{
test: /\.(ts|d\.ts)$/,
use: 'ts-loader'
}
]
}
};
16.2 Rollup集成
使用@rollup/plugin-typescript:
javascript复制import typescript from '@rollup/plugin-typescript';
export default {
plugins: [
typescript({
include: ['**/*.ts', '**/*.d.ts']
})
]
};
16.3 Babel集成
使用@babel/preset-typescript处理类型:
json复制{
"presets": [
["@babel/preset-typescript", {
"onlyRemoveTypeImports": true
}]
]
}
17. 声明文件在微前端架构中的应用
17.1 共享类型定义
创建共享类型包:
bash复制mkdir shared-types
cd shared-types
npm init -y
tsc --init --declaration
17.2 模块联邦中的类型处理
配置Webpack的ModuleFederationPlugin:
javascript复制new ModuleFederationPlugin({
name: 'app1',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/components/Button.tsx'
}
});
17.3 类型安全的跨应用通信
定义共享事件类型:
typescript复制// shared-types/src/events.ts
export interface CrossAppEvent {
type: string;
payload?: unknown;
source: string;
timestamp: number;
}
18. 声明文件与测试框架
18.1 Jest测试中的类型支持
为Jest自定义匹配器添加类型:
typescript复制declare global {
namespace jest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
18.2 Cypress类型增强
扩展Cypress命令:
typescript复制declare namespace Cypress {
interface Chainable {
login(username: string, password: string): Chainable<void>;
getByTestId(testId: string): Chainable<JQuery<HTMLElement>>;
}
}
18.3 测试工具类型共享
创建测试专用的类型声明:
typescript复制// types/testing.d.ts
declare interface TestConfig {
retries: number;
timeout: number;
env: Record<string, string>;
}
declare const testConfig: TestConfig;
19. 声明文件与文档生成
19.1 TypeDoc集成
使用TypeDoc从类型定义生成文档:
bash复制npx typedoc --out docs src/index.ts
19.2 JSDoc与类型结合
增强类型定义的文档:
typescript复制/**
* 表示一个用户实体
*/
declare interface User {
/**
* 用户唯一ID
* @minimum 1
*/
id: number;
/**
* 用户显示名称
* @maxLength 50
*/
name: string;
}
19.3 API文档自动生成
使用OpenAPI从类型定义生成API文档:
typescript复制/**
* @openapi
* components:
* schemas:
* User:
* type: object
* properties:
* id:
* type: integer
* name:
* type: string
*/
declare interface User {
id: number;
name: string;
}
20. 声明文件与性能优化
20.1 懒加载类型
使用import()类型实现懒加载:
typescript复制declare function lazyLoadModule(): Promise<{
default: typeof import('heavy-module');
}>;
20.2 类型缓存策略
配置tsconfig.json优化类型检查:
json复制{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": "./.tsbuildinfo"
}
}
20.3 项目引用优化
使用TypeScript项目引用拆分大型代码库:
json复制{
"references": [
{ "path": "./shared-types" },
{ "path": "./app" }
]
}
在Linux环境下,可以通过以下命令并行构建:
bash复制tsc --build --force --verbose
21. 声明文件与安全实践
21.1 类型安全验证
使用工具验证类型定义与实际实现的匹配:
bash复制npm install -g typescript-checker
tsc-check --project tsconfig.json
21.2 敏感数据保护
避免在类型定义中暴露敏感信息:
typescript复制declare interface Config {
// 错误:暴露了实际密钥格式
// apiKey: string;
// 正确:只声明存在配置项
apiKey?: string;
}
21.3 权限相关类型
安全地定义权限类型:
typescript复制declare type Permission = 'read' | 'write' | 'admin';
declare interface User {
permissions: Permission[];
}
22. 声明文件与国际化
22.1 多语言类型支持
为国际化库添加类型:
typescript复制declare module 'i18n' {
interface Options {
locale: string;
fallbackLocale?: string;
}
export function t(key: string, params?: Record<string, any>): string;
}
22.2 本地化资源类型
定义资源文件结构:
typescript复制declare module '*.json' {
const value: {
[key: string]: {
message: string;
description?: string;
}
};
export default value;
}
22.3 日期时间本地化
为日期处理库添加类型:
typescript复制declare module 'date-fns' {
export function format(date: Date, formatStr: string, options?: {
locale?: Locale;
weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
}): string;
}
23. 声明文件与状态管理
23.1 Redux类型增强
为Redux store添加类型:
typescript复制import { Action } from 'redux';
declare module 'redux' {
interface Store<S> {
asyncReducers: Record<string, Reducer>;
injectReducer: (key: string, reducer: Reducer) => void;
}
}
23.2 Vuex类型支持
为Vuex模块添加类型:
typescript复制import { Module } from 'vuex';
declare module 'vuex' {
interface Store<S> {
$services: {
api: any;
};
}
}
23.3 响应式状态类型
为响应式状态库添加类型:
typescript复制declare module 'reactive-state' {
interface Atom<T> {
get(): T;
set(value: T): void;
subscribe(callback: (value: T) => void): () => void;
}
export function createAtom<T>(initialValue: T): Atom<T>;
}
24. 声明文件与可视化开发
24.1 图表库类型支持
为ECharts添加自定义类型:
typescript复制declare module 'echarts' {
interface EChartOption {
customFeature?: {
enabled?: boolean;
config?: Record<string, any>;
};
}
}
24.2 地图库类型增强
为地图库添加类型:
typescript复制declare module 'leaflet' {
interface MapOptions {
customControl?: boolean;
}
namespace control {
function custom(options?: { position?: string }): Control;
}
}
24.3 可视化组件类型
为自定义可视化组件添加类型:
typescript复制declare module 'data-vis' {
interface ComponentProps {
data: Array<{ x: number; y: number }>;
width?: number;
height?: number;
onSelect?: (item: { x: number; y: number }) => void;
}
export const ScatterPlot: React.FC<ComponentProps>;
}
25. 声明文件与Web Workers
25.1 Worker类型声明
为Web Worker通信添加类型:
typescript复制// types/worker.d.ts
declare module 'worker-loader!*' {
class WebpackWorker extends Worker {
constructor();
}
export default WebpackWorker;
}
interface WorkerMessage {
type: 'calculate' | 'result' | 'error';
payload?: any;
}
25.2 线程间通信类型
定义结构化克隆的类型:
typescript复制declare interface TransferableObject {
id: string;
data: ArrayBuffer;
transfer?: Transferable[];
}
25.3 SharedWorker类型
为SharedWorker添加类型:
typescript复制declare module 'shared-worker' {
interface SharedWorkerGlobalScope {
onconnect: (event: MessageEvent) => void;
}
}
26. 声明文件与WebAssembly
26.1 WASM模块类型
为WebAssembly模块添加类型:
typescript复制declare module '*.wasm' {
const value: WebAssembly.Module;
export default value;
}
26.2 WASM导入/导出类型
定义WASM导入对象:
typescript复制declare interface WasmImports {
env: {
memory: WebAssembly.Memory;
table?: WebAssembly.Table;
abort?: (msg: number, file: number, line: number, column: number) => void;
};
}
26.3 WASM实例类型
为WASM实例添加类型:
typescript复制declare interface WasmInstance<T = any> {
exports: T;
}
27. 声明文件与Node.js原生模块
27.1 原生模块类型
为Node.js C++插件添加类型:
typescript复制declare module 'native-module' {
export function doSomethingSync(input: Buffer): Buffer;
export function doSomethingAsync(input: Buffer): Promise<Buffer>;
}
27.2 进程通信类型
为进程间通信添加类型:
typescript复制declare interface ProcessMessage {
type: 'start' | 'data' | 'end' | 'error';
payload?: any;
}
27.3 流处理类型
为自定义流添加类型:
typescript复制declare module 'custom-stream' {
import { Transform } from 'stream';
interface Options {
highWaterMark?: number;
encoding?: BufferEncoding;
}
class CustomTransform extends Transform {
constructor(options?: Options);
}
export = CustomTransform;
}
28. 声明文件与数据库交互
28.1 ORM类型增强
为Sequelize模型添加类型:
typescript复制import { Model } from 'sequelize';
declare module 'sequelize' {
interface Model {
customMethod(): this;
}
}
28.2 查询构建器类型
为查询构建器添加类型:
typescript复制declare module 'knex' {
interface QueryBuilder<TRecord, TResult> {
whereBetween(
column: string,
range: [number, number]
): QueryBuilder<TRecord, TResult>;
}
}
28.3 数据库驱动类型
为数据库驱动添加类型:
typescript复制declare module 'mongodb-driver' {
interface FindOptions {
limit?: number;
skip?: number;
projection?: Record<string, number>;
}
export class Collection {
find(filter: object, options?: FindOptions): Promise<any[]>;
}
}
29. 声明文件与机器学习
29.1 TensorFlow.js类型增强
为TF.js操作添加类型:
typescript复制declare module '@tensorflow/tfjs' {
interface Tensor {
customOp(): Tensor;
}
}
29.2 模型类型定义
为机器学习模型添加类型:
typescript复制declare interface ModelInput {
data: Float32Array;
shape: number[];
}
declare interface ModelOutput {
prediction: number;
confidence: number;
}
29.3 预处理类型
为数据预处理添加类型:
typescript复制declare module 'data-preprocessing' {
export function normalize(
data: number[],
options?: { min?: number; max?: number }
): number[];
}
30. 声明文件与区块链开发
30.1 智能合约类型
为以太坊合约添加类型:
typescript复制declare module 'ethers' {
interface Contract {
customMethod(): Promise<string>;
}
}
30.2 交易类型定义
为区块链交易添加类型:
typescript复制declare interface Transaction {
hash: string;
from: string;
to?: string;
value: string;
data?: string;
}
30.3 钱包类型增强
为加密钱包添加类型:
typescript复制declare module 'crypto-wallet' {
interface Wallet {
address: string;
signTransaction(tx: object): Promise<string>;
encrypt(password: string): Promise<string>;
}
}
31. 声明文件与游戏开发
31.1 游戏引擎类型
为游戏实体添加类型:
typescript复制declare module 'game-engine' {
interface Entity {
position: { x: number; y: number };
update(delta: number): void;
render(ctx: CanvasRenderingContext2D): void;
}
}
31.2 物理引擎类型
为物理引擎添加类型:
typescript复制declare module 'physics-engine' {
interface Body {
mass: number;
velocity: { x: number; y: number };
applyForce(force: { x: number; y: number }): void;
}
}
31.3 游戏状态类型
为游戏状态管理添加类型:
typescript复制declare interface GameState {
level: number;
score: number;
player: {
health: number;
position: { x: number; y: number };
};
}
32. 声明文件与AR/VR开发
32.1 WebXR类型增强
为WebXR会话添加类型:
typescript复制declare module 'webxr' {
interface XRSession {
customFeature?: {
enabled: boolean;
};
}
}
32.2 3D模型类型
为3D模型加载添加类型:
typescript复制declare module '3d-loader' {
interface Model {
meshes: Array<{
vertices: Float32Array;
indices?: Uint16Array;
}>;
materials?: Array<{
diffuse: [number, number, number];
}>;
}
}
32.3 交互事件类型
为AR/VR交互添加类型:
typescript复制declare interface XRInteractionEvent {
type: 'select' | 'hover' | 'move';
position: [number, number, number];
inputSource?: XRInputSource;
}
33. 声明文件与音视频处理
33.1 Web Audio类型增强
为音频节点添加类型:
typescript复制declare module 'webaudio' {
interface AudioContext {
createCustomNode(options?: { bufferSize?: number }): AudioNode;
}
}
33.2 视频处理类型
为视频分析添加类型:
typescript复制declare module 'video-analysis' {
export function detectMotion(
video: HTMLVideoElement,
options?: { threshold?: number }
): Promise<{ motionAreas: Array<{ x: number; y: number; width: number; height: number }> }>;
}
33.3 流媒体类型
为媒体流添加类型:
typescript复制declare interface MediaStreamInfo {
codec: string;
bitrate: number;
resolution?: { width: number; height: number };
}
34. 声明文件与物联网开发
34.1 设备通信类型
为IoT设备协议添加类型:
typescript复制declare module 'iot-protocol' {
interface DeviceMessage {
deviceId: string;
timestamp: number;
payload: Record<string, any>;
}
}
34.2 传感器数据类型
为传感器数据添加类型:
typescript复制declare interface SensorReading {
type: 'temperature' | 'humidity' | 'pressure';
value: number;
unit: string;
timestamp: number;
}
34.3 边缘计算类型
为边缘计算节点添加类型:
typescript复制declare module 'edge-compute' {
export function processData(
data: Array<{ timestamp: number; value: number }>,
config?: { windowSize?: number }
): Promise<{ average: number; max: number; min: number }>;
}
35. 声明文件与函数式编程
35.1 函数组合类型
为函数组合工具添加类型:
typescript复制declare module 'fp-tools' {
export function compose<T1, T2, T3>(
f: (x: T2) => T3,
g: (x: T1) => T2
): (x: T1) => T3;
}
35.2 代数数据类型
为ADT添加类型:
typescript复制declare type Maybe<T> = Just<T> | Nothing;
declare interface Just<T> {
type: 'just';
value: T;
}
declare interface Nothing {
type: 'nothing';
}
35.3 不可变数据类型
为不可变数据结构添加类型:
typescript复制declare module 'immutable-data' {
interface List<T> {
push(item: T): List<T>;
get(index: number): T | undefined;
size: number;
}
}
36. 声明文件与编译器开发
36.1 AST类型定义
为抽象语法树添加类型:
typescript复制declare interface ASTNode {
type: string;
loc?: {
start: { line: number; column: number };
end: { line: number; column: number };
};
}
declare interface Identifier extends ASTNode {
type: 'Identifier';
name: string;
}
36.2 解析器类型
为语法解析器添加类型:
typescript复制declare module 'parser-generator' {
export function createParser(
grammar: string,
options?: { memoization?: boolean }
): (input: string) => ASTNode;
}
36.3 代码生成类型
为代码生成器添加类型:
typescript复制declare interface CodeGenOptions {
indent?: number;
sourceMap?: boolean;
comments?: boolean;
}
declare function generateCode(node: ASTNode, options?: CodeGenOptions): string;
37. 声明文件与安全审计
37.1 漏洞模式类型
为安全审计添加类型:
typescript复制declare interface VulnerabilityPattern {
id: string;
description: string;
severity: 'low' | 'medium' | 'high' | 'critical';
pattern: RegExp;
}
37.2 审计结果类型
为审计结果添加类型:
typescript复制declare interface AuditResult {
file: string;
line: number;
column: number;
pattern: VulnerabilityPattern;
context: string;
}
37.3 安全规则类型
为自定义安全规则添加类型:
typescript复制declare module 'security-audit' {
export function addRule(rule: {
id: string;
check: (code: string) => AuditResult[];
}): void;
}
38. 声明文件与性能分析
38.1 性能指标类型
为性能指标添加类型:
typescript复制declare interface PerformanceMetrics {
loadTime: number;
fps?: number;
memoryUsage?: {
heapUsed: number;