微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

tsconfig 中的路径无法导入类型

如何解决tsconfig 中的路径无法导入类型

我正在使用 TypeScript 进行服务器端项目。 我在 ooo.d.ts 中定义了一些类型。我在 paths 中设置了 tsconfig.json。 但是当我尝试导入我定义的类型时,它显示错误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 ... 可用于添加或扩充某些外部模块的声明(通常通过 package.json 安装或在“构建”期间生成)。

但这里的情况并非如此,文件/模块是项目的一部分,您只需删除 declare module "express-custom-types" 包装器即可。

,

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。