index.d.ts类型定义在编译时被tsc忽略

huangapple go评论68阅读模式
英文:

index.d.ts type definitions being ignored by tsc when compiling

问题

以下是您要翻译的内容:

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

然而,我面临的问题是,tsc似乎忽略了我创建的index.d.ts文件,并且无法改变Express Request对象。

这是我的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

这导致在使用它的每个控制器中多次出现以下错误:

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

I have an Express app built in TypeScript that I'm attempting to compile using the tsc CLI tool.

An issue that I'm facing, however, is that tsc seems to ignore the index.d.ts file that I've created and used to mutate the Express Request object.

This is my index.d.ts file:

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

This allows me to do stuff like this inside my controller's requests without TypeScript spitting out a does not exist error:

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

I'm running the following command to build my app:

tsc ./Main.ts --outdir build

Which results in the following error multiple times across every controller that uses it:

error TS2339: Property &#39;foo&#39; does not exist on type &#39;Request&lt;ParamsDictionary, any, any, ParsedQs, Record&lt;string, any&gt;&gt;&#39;.

答案1

得分: 1

尝试在你的index.d.ts文件中添加一个空的导出:

export {};

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

Try adding an empty export to your index.d.ts file:

export {};

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

huangapple
  • 本文由 发表于 2023年1月9日 07:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定