node.js - 编译时 tsc 忽略 index.d.ts 类型定义

标签 node.js typescript express tsc

我有一个用 TypeScript 构建的 Express 应用程序,我正在尝试使用 tsc 进行编译。 CLI 工具。

但是,我面临的一个问题是,tsc 似乎忽略了我创建并用于改变的 index.d.ts 文件表达 Request 对象。

这是我的 index.d.ts 文件:

declare global{
    namespace Express{
        export interface Request{
            foo: string;
        }
    }
}

这允许我在 Controller 的请求中执行类似的操作,而 TypeScript 不会抛出 不存在 错误:

export const example = async (req: Request) => {
    const { foo } = req;
    // Outputs "bar". This works completely fine in development.
    console.log(foo);
};

我正在运行以下命令来构建我的应用程序:

tsc ./Main.ts --outdir build

这会导致使用它的每个 Controller 多次出现以下错误:

error TS2339: Property 'foo' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

最佳答案

尝试向您的index.d.ts 文件添加一个空导出:

export {};

declare global{
    namespace Express{
        export interface Request{
            foo: string;
        }
    }
}

关于node.js - 编译时 tsc 忽略 index.d.ts 类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75051941/

相关文章:

android - 退出 Expo 后无法运行 React Native 应用程序

javascript - 如何将 Angular 资源文件夹中的 js 文件加载到特定的 Angular(2,4,5) 组件或模块?

json - 在node.js中获取IP的ISP

node.js - Azure 应用服务上使用 Node-sass 的 Express 应用

node.js - Npm Express 模块未安装

javascript - 在 MongoDB 中,当使用多个参数进行搜索时,如何知道哪个参数匹配

javascript - ReactJS 与 Webpack : Uncaught ReferenceError: require is not defined

node.js - TypeScript 类型错误(错误 TS2687): All declarations of 'iterator' must have identical modifiers

javascript - 如何停止在 MySQL 中舍入 int 值

javascript - 从其他类访问静态方法是标准的吗?