【发布时间】:2021-01-07 18:08:31
【问题描述】:
我有带有 Express 和 Typescript 的 NodeJs 应用程序。我正在尝试从 Express 扩展 Request 类型。
我用下面的代码创建了 index.d.ts
import { User } from "models/user";
declare global {
namespace Express {
export interface Request {
currentUser: User
}
}
}
我的代码编辑器(我使用 VSCode)告诉我一切都很好,并且自动完成功能很好。 但在运行时打字稿抛出错误
src/api/controllers/post.controller.ts:60:24 - error TS2339: Property 'currentUser' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
我找到了以下代码,解决了我的问题
import { User } from 'models/user';
declare module "express-serve-static-core" {
export interface Request {
currentUser: User
}
}
我必须将此代码复制到我的应用程序的任何文件中,它可以工作。但我不明白为什么它会起作用。谁能解释为什么会发生这种情况以及为什么第一个解决方案不起作用?
我使用 ts-node 包运行我的应用程序。 ts-node ./src/index.ts
tsconfig.json
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs",
"strict": true,
"baseUrl": "./src",
"typeRoots": [
"./src/@types",
"./node_modules/@types",
],
"types": ["reflect-metadata"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": [
"node_modules"
]
}
【问题讨论】:
标签: typescript express