【问题标题】:TypeScript - Cannot import self in types override in other types root, TS7016TypeScript - 无法在其他类型根中导入自我类型覆盖,TS7016
【发布时间】:2019-02-27 01:02:39
【问题描述】:

我正在使用 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),其中包含来自 distinctlyTyped 类型的精确副本。

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

TS7016 找不到模块“@feathersjs/feathers”的声明文件。 'C:/Users/marek/dev/system/api - kopia/node_modules/@feathersjs/feathers/lib/index.js' 隐含地具有“任何”类型。 尝试npm install @types/feathersjs__feathers(如果存在)或添加包含declare module 'feathersjs__feathers'; 的新声明(.d.ts)文件

我尝试将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,我在那里有自己的打字,它们工作正常。问题只是导入自我......

【问题讨论】:

    标签: node.js typescript feathersjs


    【解决方案1】:

    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“相关”小部件找到了 an answer,它基本上回答了您的问题,尽管 IMO 不像我的回答那么清楚。)

    【讨论】:

    • 这需要记录在案。我试图加载一个从node_modules 复制出来的类型包,并希望能够在typeRoots 中包含my/custom/path,并让它解析与node_modules 完全相同的类型。请更新此页面! typescriptlang.org/docs/handbook/tsconfig-json.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2017-06-13
    • 2013-08-15
    • 2017-08-22
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多