插件窝 干货文章 如何用TypeScript类型声明实现JS工具函数库的类型提示?

如何用TypeScript类型声明实现JS工具函数库的类型提示?

类型 TypeScript 函数 number 56    来源:    2025-03-19

要在 TypeScript 中实现 JavaScript 工具函数库的类型提示,你可以通过以下步骤来完成:

1. 创建 TypeScript 声明文件

首先,你需要为你的 JavaScript 工具函数库创建一个 TypeScript 声明文件(.d.ts)。这个文件将包含所有函数的类型声明。

假设你的工具函数库名为 utils.js,你可以创建一个名为 utils.d.ts 的文件。

2. 定义函数类型

utils.d.ts 文件中,你需要为每个工具函数定义类型。例如,假设你的 utils.js 中有以下函数:

// utils.js
function add(a, b) {
    return a + b;
}

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

你可以在 utils.d.ts 中这样定义类型:

// utils.d.ts
declare function add(a: number, b: number): number;
declare function capitalize(str: string): string;

3. 导出类型

如果你的工具函数库是通过模块导出的,你还需要在声明文件中使用 export 关键字来导出这些类型。

// utils.d.ts
export function add(a: number, b: number): number;
export function capitalize(str: string): string;

4. 使用类型声明

在你的 TypeScript 项目中,你可以通过导入 utils.js 来使用这些工具函数,并且 TypeScript 会自动识别 utils.d.ts 中的类型声明。

import { add, capitalize } from './utils';

const result = add(1, 2); // result 的类型会被推断为 number
const capitalized = capitalize('hello'); // capitalized 的类型会被推断为 string

5. 全局声明(可选)

如果你的工具函数库是全局可用的(即不需要导入),你可以在声明文件中使用 declare global 来声明全局类型。

// utils.d.ts
declare global {
    function add(a: number, b: number): number;
    function capitalize(str: string): string;
}

这样,你可以在任何 TypeScript 文件中直接使用 addcapitalize 函数,而不需要导入。

6. 使用 JSDoc 注释(可选)

如果你希望在 JavaScript 文件中直接提供类型提示,你可以使用 JSDoc 注释来定义类型。TypeScript 会自动识别这些注释并提供类型提示。

// utils.js
/**
 * Adds two numbers.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @returns {number} The sum of the two numbers.
 */
function add(a, b) {
    return a + b;
}

/**
 * Capitalizes the first letter of a string.
 * @param {string} str - The string to capitalize.
 * @returns {string} The capitalized string.
 */
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

7. 配置 TypeScript 项目

确保你的 tsconfig.json 文件中包含了正确的配置,以便 TypeScript 能够识别你的声明文件。

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

总结

通过创建 TypeScript 声明文件(.d.ts)并在其中定义工具函数的类型,你可以为 JavaScript 工具函数库提供完整的类型提示。这样,在使用这些函数时,TypeScript 可以提供类型检查和自动补全功能,从而提高开发效率和代码质量。