为纯 javascript 项目添加 typescript 类型的核心是编写 .d.ts 声明文件,它不生成运行时代码,仅提供类型信息供 ts 编译器和编辑器使用;支持全局声明、模块声明、第三方包类型补充及 js 文件类型检查。

给纯 JavaScript 项目添加 TypeScript 类型,核心是编写 .d.ts 声明文件。它不生成运行时代码,只提供类型信息,让 TS 编译器和编辑器(如 VS Code)能理解 JS 的结构。
声明全局变量或函数
适用于直接挂载在 window 上、或通过 <script></script> 引入的库(比如 jQuery、Lodash 或自定义工具库)。
在项目根目录新建 global.d.ts(或任意 .d.ts 文件,确保被 TS 配置包含):
declare const $: {
(selector: string): HTMLElement[];
ajax(url: string, options?: any): Promise<any>;
};
<p>declare function debounce(fn: Function, wait: number): Function;</p></any>这样在任意 .ts 或启用了类型检查的 .js 文件中,就能获得 $ 和 debounce 的类型提示和校验。
为现有 JS 模块写模块声明
如果你有一个 JS 文件 utils.js,内容如下:
// utils.js
export function formatDate(date, format) { /* ... */ }
export const version = '1.2.0';在同一目录下创建 utils.d.ts:
// utils.d.ts export function formatDate(date: Date | string, format: string): string; export const version: string;
TS 会自动匹配同名的 .js 和 .d.ts 文件。注意:导出签名必须完全一致(包括参数名可省略,但类型和顺序不能错)。
为 node_modules 中的纯 JS 包补充类型
很多 npm 包没有内置类型(如 axios 旧版、dayjs 插件等)。可手动补全:
- 在项目里建
types/目录,例如types/dayjs-plugin-advanced-format/index.d.ts - 在
tsconfig.json中配置路径映射:
"compilerOptions": {
"typeRoots": ["node_modules/@types", "types"]
}然后在声明文件中使用模块增强或全新声明:
// types/dayjs-plugin-advanced-format/index.d.ts
import dayjs from 'dayjs';
<p>declare module 'dayjs' {
interface Dayjs {
advancedFormat(): string;
}
}</p>启用 JS 文件的类型检查(可选但推荐)
在 tsconfig.json 中开启:
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"skipLibCheck": true
}再在 JS 文件顶部加 // @ts-check,就能在 JS 中享受类型提示和错误标记;配合 /// <reference types="./my-utils.d.ts"></reference> 可显式引入自定义声明。











