我有一个用 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/