d.ts文件无法识别

比如我给window全局扩展了一个属性
demo/global.d.ts

declare  global {
  interface Window {
    $electron: any;
  }
}

export {}; // 修复:全局范围的扩大仅可直接嵌套在外部模块中或环境模块声明中

但是编辑器依然不会识别

这是因为你的类型文件并没有被ts加载,需要修改如下
tsconfig.json 或 tsconfig.app.json 中修改如下

{
   //...
  "include": ["global.d.ts", ...]
}

其它注意

识别为模块文件

声明文件 *.d.ts 里,不使用 import export 等 es6 模块化相关语法,因为开发环境会把当前文件识别成模块 而非类型文件。

两种写法

方式1(推荐)

// 提取类型定义
type ElectronType = { [key: string]: any };

interface Window { //扩展widow全局对象属性声明
  $electron: ElectronType;
}
declare const $electron: ElectronType; // 声明全局变量

方式2

这会将此文件识别为模块化文件,需要你导出一个空来防止报错

declare global {
  interface Window {
    $electron: ElectronType;
  }
  const $electron: ElectronType; // 声明全局变量
}


export {}; // 修复:全局范围的扩大仅可直接嵌套在外部模块中或环境模块声明中

两种方式都可以让一下代码正常被识别编译

<script setup lang="ts">
  console.log($electron);
  console.log(window.$electron); 
</script>

如何省略window访问全局对象

ts.config.js

{
  "compilerOptions": {
   
    "lib": [..., "DOM", "DOM.Iterable"],
     // ...
}

这样你就可以直接在js中使用 location.href等全局方法或属性,而不用window.location.href

posted @ 2024-12-28 18:00  丁少华  阅读(313)  评论(0)    收藏  举报