You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为npm scoped作用域包配置自定义TypeScript类型声明

解决方案

1. 调整tsconfig配置

在compilerOptions中新增typeRoots配置,显式指定TypeScript查找类型定义的目录,修改后配置如下:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "baseUrl": "src",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    // 新增以下配置
    "typeRoots": ["src/types", "node_modules/@types"]
  },
  "include": [
    "src"
  ]
}

2. 确认类型文件规则

  • 类型文件路径使用src/types/@example-org/react-date-range/index.d.ts即可,不需要使用双下划线命名格式。
  • 如果类型文件中没有任何顶层的import/export语句,直接写模块声明即可:
declare module "@example-org/react-date-range" {
  // 复用你之前写的所有react-date-range类型定义即可
}
  • 如果类型文件中需要导入其他类型(比如React的类型),需要把模块声明包在declare global块中,避免全局声明失效:
import type { ReactNode } from "react";

declare global {
  declare module "@example-org/react-date-range" {
    // 你的类型定义
  }
  // 如果有导入子模块的需求(比如导入包内的样式),可以补充对应声明
  declare module "@example-org/react-date-range/dist/*.css" {}
}

3. 生效验证

修改完成后执行以下操作清除缓存:

  1. 删除本地缓存目录:rm -rf node_modules/.cache
  2. 如果你使用VSCode开发,按Ctrl+Shift+P(Mac为Cmd+Shift+P),选择TypeScript: Restart TS Server重启语言服务即可。

内容的提问来源于stack exchange,提问作者Hugo Licón

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 14:30:02