【问题标题】:Typescript extend Request type from ExpressTypescript 从 Express 扩展请求类型
【发布时间】: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


    【解决方案1】:

    对于较新版本的 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
      }
    }
    

    【讨论】:

    • 我应该在哪里写这个声明?因为如果我在 index.d.ts 中复制此代码,它将不起作用。我认为将此代码粘贴到应用程序的入口点有点乱。
    • 与@types/express/index.d.ts 也不起作用:(
    • 是的,我试过src/@types/express/index.d.ts、src/@types/index.d.ts,但没有用。
    猜你喜欢
    • 2019-05-30
    • 2021-01-12
    • 2017-11-23
    • 2017-02-26
    • 2020-09-21
    • 1970-01-01
    • 2021-06-05
    • 2021-03-25
    • 2021-04-08
    相关资源
    最近更新 更多