【问题标题】:paths in tsconfig cannot import the typetsconfig 中的路径无法导入类型
【发布时间】:2021-01-19 15:08:41
【问题描述】:

我正在使用 TypeScript 处理服务器端项目。 我在ooo.d.ts中定义了一些类型。我在tsconfig.json 中设置了paths。 但是当我尝试导入我定义的类型时,它显示错误,Module '"../../@types/express-custom-types"' has no exported member 'CustomError'.

项目结构如下。

├── src
│   └── routes
│       └── errorHandlers.ts
├── tsconfig.json
└── @types
    └── express-custom-types
        └── index.d.ts

我在index.d.ts 中定义类型,如下所示。

declare module "express-custom-types" {
  export type ErrorBody = { type: string; status: number; message: string };
}

我在 tsconfig.json 中定义了别名

"compilerOptions": {
    ...(omit)...

    "baseUrl": "./",
    "paths": {
      "*": ["*"],
      "@custom-types/*": ["@types/*"],
    },

然后像这样导入errorHandlers.ts中的类型。

import { ErrorBody } from "@custom-types/express-custom-types";

但它显示错误Module '"../../@types/express-custom-types"' has no exported member 'ErrorBody'.

我不知道该怎么办..

【问题讨论】:

  • 删除 declare module "express-custom-types" 包装。你为什么需要它?我猜没有这样的模块
  • @AlekseyL。非常感谢你。这对我有用:) 那么我什么时候应该使用declare module 语法?顺便说一句,请写下您的评论作为答案,然后我会接受。
  • 在答案中添加了更多信息

标签: node.js typescript express tsconfig type-declaration


【解决方案1】:

declare module ... 可用于添加或扩充某些外部模块的声明(通常通过package.json 安装或在“构建”期间生成)。

但这不是这里的情况,文件/模块是项目的一部分,你可以删除 declare module "express-custom-types" 包装器。

【讨论】:

    【解决方案2】:

    您要确保您声明的模块与您尝试导入的模块具有相同的全名。这应该有效:

    declare module "@custom-types/express-custom-types" {
      export type ErrorBody = { type: string; status: number; message: string };
    }
    

    【讨论】:

    • 对不起,我忘了告诉你们我的 tsconfig.json 设置。 "paths": { "@custom-types/*": ["@types/*"], } 但是现在,对我的问题的评论解决了它。无论如何谢谢:)
    猜你喜欢
    • 2019-01-28
    • 2019-07-20
    • 2022-01-12
    • 2020-05-06
    • 2020-12-02
    • 2022-10-06
    • 1970-01-01
    • 2023-03-18
    • 2019-04-09
    相关资源
    最近更新 更多