首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >来自Express的Typescript扩展请求类型

来自Express的Typescript扩展请求类型
EN

Stack Overflow用户
提问于 2020-09-21 23:52:28
回答 1查看 205关注 0票数 1

我有NodeJs应用程序与Express和Typescript。我正在尝试扩展Express的请求类型。

我用下面的代码创建了index.d.ts

代码语言:javascript
运行
复制
import { User } from "models/user";

declare global {
  namespace Express {
    export interface Request {
      currentUser: User
    }
  }
}

我的代码编辑器(我使用VSCode)告诉我一切都很好,自动完成功能很好。但在运行时typescript抛出错误

代码语言:javascript
运行
复制
src/api/controllers/post.controller.ts:60:24 - error TS2339: Property 'currentUser' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

我找到了以下代码,它解决了我的问题

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
{
  "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"
  ]
}
EN

回答 1

Stack Overflow用户

发布于 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

代码语言:javascript
运行
复制
import { Express } from "express-serve-static-core";

declare module 'express-serve-static-core' {
  interface Request {
    myField?: string
  }
  interface Response {
    myField?: string
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63995785

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档