【问题标题】:TypeScript cannot find namespace in Node.js dependencyTypeScript 在 Node.js 依赖项中找不到命名空间
【发布时间】:2021-09-29 19:00:18
【问题描述】:

我有两个包含类型声明文件的 node.js 包。 我在包a 中声明了一个命名空间,我想在包b 中引用它。

包A

index.d.ts

declare namespace foo {
    export interface A {}
}

package.json

{
  "name": "a",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "types": "index.d.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

包B

index.d.ts

declare namespace bar {
    const A: foo.A;
}

package.json

{
  "name": "b",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "a": "file:../a"
  }
}

错误

$ cd b
$ npm install
$ tsc --noEmit index.d.ts

index.d.ts:3:14 - error TS2503: Cannot find namespace 'foo'.

3     const A: foo.A;
               ~~~


Found 1 error.

如何获取包b 以查看包a 中声明的namespace?这是一个代码库https://github.com/icholy/typescript_problem_example

【问题讨论】:

  • foo 在哪里声明?你是说thing
  • 我已经更新了示例

标签: node.js typescript typescript-typings


【解决方案1】:

我找到的最干净的解决方案是将模块作为类型导入。

declare namespace bar {
    type _ = import('a');
    const A: foo.A;
}

另一种解决方案是使用Tripple-Slash Directive 添加对a 的直接引用。

/// <reference types="a" />

declare namespace bar {
    const A: foo.A;
}

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2023-03-20
    • 2012-10-16
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 2015-04-11
    相关资源
    最近更新 更多