首页 > 解决方案 > TypeScript 在 Node.js 依赖项中找不到命名空间

问题描述

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

套餐A

索引.d.ts

declare namespace foo {
    export interface A {}
}

包.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

索引.d.ts

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

包.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以查看包中namespace声明的内容a?这是一个带有代码https://github.com/icholy/typescript_problem_example的仓库

标签: node.jstypescripttypescript-typings

解决方案


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

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

另一种解决方案是使用三斜杠指令添加对a.

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

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

推荐阅读