• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
逍遥汉
博客园    首页    新随笔    联系   管理    订阅  订阅

TypeScript 中 Type 'typeof globalThis' has no index signature 错误解决

TypeScript 中 Type 'typeof globalThis' has no index signature 错误解决

当我们尝试访问 global 对象上不存在的属性时,会出现错误“Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature”。 要解决此错误,需要扩展全局对象并为必要的属性指定类型。

下面代码是一个发生该错误的示例。

// Error: Element implicitly has an 'any'
// type because type 'typeof globalThis'
// has no index signature.ts(7017)
global.hello = 'world';

我们试图访问 global 对象上不存在的属性,因此会看到报错。

为了解决这个问题,我们必须为我们打算在 global 对象上访问的属性和方法添加类型。

在 src 目录中,创建一个包含以下 index.d.ts 文件的 types 目录:

src/types/index.d.ts

/* eslint-disable no-var */

declare global {
  var example: string;
  function sum(a: number, b: number): number;
}

export {};

我们添加了一个 example 属性,该属性具有字符串类型和 sum 方法。

注意 ,这在不同的用例中会有所不同,因此请确保调整属性名称和类型。

确保使用 var 关键字为你打算在其他文件中设置和使用的属性添加类型。

我们需要在全局对象上添加要访问的所有属性的名称和类型。

例如,如果不知道特定属性的类型并想关闭类型检查,需要将其设置为 any。

现在,我可以设置和访问 global 对象上的指定属性,而不会出现任何错误。

global.example = 'hello world';

global.sum = function (a: number, b: number) {
  return a + b;
};

console.log(global.example); // "hello world"

console.log(global.sum(15, 25)); // 40

注意,如果您使用的是 ts-node,那么终端可能仍会出现错误。

问题在于 ts-node 无法识别本地声明文件。

要解决这个问题,请在 ts-node 命令中使用 --files 标志,因此应该运行 ts-node --files ./src/index.ts 而不是 ts-node ./src/index.ts。

将 nodemon 与 ts-node 一起使用,下面是我的 nodemon.json 文件的内容

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node --files ./src/index.ts"
}

跟上 --files 选项后(仅在使用 ts-node 时才需要),重新启动服务器,应该会一切顺利。

注意 ,这使得 sum 函数和 example 属性可以直接访问,也可以在 global 对象上访问。

global.example = 'hello world';

global.sum = function (a: number, b: number) {
  return a + b;
};

console.log(global.example); // "hello world"
console.log(global.sum(15, 25)); // 40

console.log(example); // "hello world"
console.log(sum(5, 15)); // 20

如果您的 IDE 中仍然出现错误,请尝试将 types 目录的路径添加到 tsconfig.json 文件中。

{
  "compilerOptions": {
    // ... rest
    "typeRoots": ["./node_modules/@types", "./src/types"]
  }
}

我们在 index.d.ts 文件中使用 export {} 将其标记为外部模块。 模块是包含至少 1 个导入或导出语句的文件。 我们必须这样做才能扩大 global 的范围。

注意 ,我们必须根据用例更改 index.d.ts 文件的内容。

你应该在全局对象上添加打算访问的所有属性的名称(和类型)。

src/types/index.d.ts

declare global {
  var example: any; // 禁用属性的类型检查
  function sum(a: number, b: number): number;
}

export {};

提供的文件只是添加了一个类型为 any 的 example 属性和一个 sum 方法,这很可能不是我们需要的。

TypeScript 在查找常规  .ts 文件的相同位置查找  .d.ts 文件,这取决于 tsconfig.json 文件中的 include 和 exclude 设置。

TypeScript 会将你在 global 对象上声明的类型与原始类型合并,因此你将能够从两个声明中访问属性和方法。

转载自:https://www.jiyik.com/tm/xwzj/web_928.html

时间如白驹过隙,忽然而已,且行且珍惜......
posted @ 2024-04-17 14:24  unfetteredman  阅读(714)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3