我有NodeJs应用程序与Express和Typescript。我正在尝试扩展Express的请求类型。
我用下面的代码创建了index.d.ts
import { User } from "models/user";
declare global {
  namespace Express {
    export interface Request {
      currentUser: User
    }
  }
}我的代码编辑器(我使用VSCode)告诉我一切都很好,自动完成功能很好。但在运行时typescript抛出错误
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"
  ]
}发布于 2020-09-22 04:25:36
对于较新版本的express,您需要扩充express-serve-static-core模块。
这是必需的,因为现在Express对象来自那里:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8fb0e959c2c7529b5fa4793a44b41b797ae671b9/types/express/index.d.ts#L19
基本上,使用以下代码:
@types/express/index.d.ts
import { Express } from "express-serve-static-core";
declare module 'express-serve-static-core' {
  interface Request {
    myField?: string
  }
  interface Response {
    myField?: string
  }
}https://stackoverflow.com/questions/63995785
复制相似问题