You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用tsc编译TypeScript Express应用时index.d.ts被忽略的问题

TypeScript编译Express应用时忽略自定义Request扩展声明的问题

我用TypeScript构建了一个Express应用,尝试用tsc CLI工具编译,但遇到了问题:tsc似乎完全忽略了我用来扩展Express Request对象的index.d.ts文件。

我的index.d.ts文件内容如下:

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

开发阶段,这段声明能正常工作——控制器里可以直接这样写,不会触发TypeScript的“属性不存在”错误:

export const example = async (req: Request) => {
    const { foo } = req;
    // 输出"bar",开发阶段完全正常
    console.log(foo);
};

我用以下命令构建应用:

tsc ./Main.ts --outdir build

但编译时,每个用到req.foo的控制器都会多次报出如下错误:

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

解决方法

1. 确保类型声明文件被TypeScript识别

  • 检查tsconfig.json中的include配置,确保包含了index.d.ts所在的目录。示例配置:
    {
      "include": ["src/**/*", "./index.d.ts"]
    }
    
  • 如果没有tsconfig.json,建议创建一个,避免直接用tsc命令行参数导致的配置缺失。

2. 避免直接指定单个入口文件编译

当前命令tsc ./Main.ts --outdir build仅编译Main.ts,TypeScript不会自动查找关联的类型声明文件。可以改用以下方式:

  • 配合tsconfig.json执行编译:tsc --outdir build
  • 或者在命令中包含类型声明文件:tsc ./Main.ts ./index.d.ts --outdir build

3. 确认类型声明文件的写法合规

不要给.d.ts文件添加export语句,否则会变成模块类型,无法扩展全局的Express接口。你当前使用declare global的写法是正确的,保持即可。


内容的提问来源于stack exchange,提问作者Grover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:01:03