global.d.ts 无效问题解决

问题描述

src 同级目录有一个 types目录,其中包含 global.d.ts,如下

js 复制代码
declare global {
  interface Window {
    config: {
      url: string;
    };
  }
}

在组件中访问

js 复制代码
window.config = 'x';

ts显示此错误

js 复制代码
Error:(10, 22) TS2339: Property 'config' does not exist on type 'Window'.

我的tsconfig.json如下

json 复制代码
{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "jsxImportSource": "vue",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "baseUrl": "./",
    "allowJs": true,
    "forceConsistentCasingInFileNames": true,
    "allowSyntheticDefaultImports": true,
    "strictFunctionTypes": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "skipLibCheck": true,
    "paths": {
      "@/*": ["src/*"]
    },
    "types": [
      "vite/client"
    ]
  },
  "include": ["src", "types/**/*.d.ts"],
  "exclude": ["dist", "node_modules"]
}

问题解决

方法1

一种简单的方法是从你的 global.d.ts 导出一个空对象,如下所示:

js 复制代码
declare global {
  interface Window {
    config: {
      url: string;
    };
  }
}

// 添加此语句后,Typescript/CRA可以提取声明文件:
export {}

方法2

如果你的.d.ts文件不导入或导出任何内容,您可以省略该declare global块。

你需要确保此文件位于@types目录中,或者你已配置typeRoots为包含类型声明的目录,例如

js 复制代码
{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types/",
      "./types/"
    ]
  }
}
相关推荐
Json____9 小时前
vue3-商城管理系统-前端静态网站
前端·vue3·ts·商城纯静态
Huanzhi_Lin25 天前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
belldeep1 个月前
nodejs:Vite + Svelte + ts 入门示例
typescript·node.js·ts·vite·svelte
却道天凉_好个秋2 个月前
音视频学习(九十二):ts封装
音视频·ts
zh_xuan2 个月前
React Native Demo
android·javascript·react native·ts
我讲个笑话你可别哭啊3 个月前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
cui_win3 个月前
企业级中后台开源解决方案汇总
开源·vue3·ts
麷飞花4 个月前
TypeScript问题
前端·javascript·vscode·typescript·ts
千里马-horse4 个月前
Rect Native bridging 源码分析--AString.h
c++·ts·rn·jsi
小白_ysf4 个月前
Vue3+TS项目中高德地图组件封装(集成关键词搜索、输入提示、标记点、信息弹窗和数据回显)
vue3·ts·高德·地图 js api