TypeScript - 无法在其他类型根目录中的类型覆盖中导入自身,TS7016

TypeScript - Cannot import self in types override in other types root, TS7016

我正在使用 FeathersJS 和 TypeScript。 由于它仍在开发中(TS for Feathers),我发现我需要重写类型才能适应我的情况(例如,可以禁用或启用分页,类型应该处理它但目前不处理) .

在我的 tsconfig.json 中,我有以下内容:

"typeRoots": [                            /* List of folders to include type definitions from. */
      "./types",
      "node_modules/@types"
    ],

顺序无关紧要,因为我也先尝试过 node_modules。

我把文件夹 feathersjs__feathers 放在 ./types 中,只有 index.d.ts(删除了 package.json)以及 DefinitelyTyped 类型的精确副本。

这一行导致了问题:import * as self from '@feathersjs/feathers';

TS7016 could not find a declaration file for module '@feathersjs/feathers'. 'C:/Users/marek/dev/system/api — kopia/node_modules/@feathersjs/feathers/lib/index.js' implicitly has an 'any' type.   Try npm install @types/feathersjs__feathers if it exists or add a new declaration (.d.ts) file containing declare module 'feathersjs__feathers';

我试过将 package.json 添加到我的文件夹中,就像这样:

{
  "name": "@types/feathersjs__feathers",
  "version": "0.0.1",
  "types": "index.d.ts"
}

但这对解决这个问题没有帮助。 如果我安装 @types/feathersjs__feathers 所以它在 node_modules 中就没有错误,但无论 typeRoots 中的顺序如何,它都从该类型中获取类型,而不是从我的覆盖中获取类型。

有什么解决办法吗?

通常 ./types 的配置和 index.d.ts 的文件夹都可以,例如对于 feathers-mongoose 我在那里有自己的打字,它们工作正常。问题在于导入自我...

typeRoots 仅帮助 TypeScript 编译器找到要为 types 选项(或 /// <reference types="..."/> 指令)加载的文件,以便于任何 declare module "..." { ... } 和全局声明他们包含。但是 @feathersjs/feathersindex.d.ts 文件不使用 declare module "..." { ... };它旨在通过 TypeScript 的主要模块解析过程作为模块本身找到。该进程不遵守 typeRoots,当它在 node_modules 中找到未类型化的模块时,它会硬连接到 node_modules/@types 中查找。要让模块分辨率看起来在一个额外的地方,你必须使用 baseUrlpaths 选项:

{
    "compilerOptions": {
        // ...
        "baseUrl": ".",
        "paths": {
            "@feathersjs/feathers": ["types/feathersjs__feathers"]
        }
    }
}

这对我来说似乎是糟糕的设计,但是 the TypeScript team has already said once that the behavior is intentional,所以我认为不值得提交错误来要求他们更改它。

(我注意到 Stack Overflow "Related" 小部件发现 基本上回答了你的问题,尽管在我看来它不像我的回答那么清楚。)