Express + TypeScript:为response.locals创建类型推断

问题描述 投票:0回答:3

我想为我的

response.locals
添加类型。它用于将数据附加到您的请求-响应周期中。

我尝试了什么

// ./types/express/index.d.ts
declare global {
    declare namespace Express {
        interface Response {
            locals: {
                userId: number;
            };
        }
    }
}

// tsconfig.json
    "compilerOptions": {
        "typeRoots": ["./types"],
    }
myController.post("/", async (request, response) => {
     // Can't get type in my controller
    const { userId } = response.locals; // <- userId is any

目标:为我的

response.locals
变量获得正确的类型推断

版本:

"express": "^4.17.1",
"@types/express": "^4.17.8",
"typescript": "^4.5.4"

node.js typescript express
3个回答
7
投票

查看

@types/express-serve-static-core/index.d.ts
,我们可以看到有一个全局命名空间
Express
,其中包含一些我们可以扩展的接口。其中之一是
Locals
:)

解决方案:

src/types.d.ts
(或类似的,将其包含在 tsconfig 中,例如在“类型”字段中)

declare global {
  namespace Express {
    interface Locals {
      anything: 'here'
    }
  }
}

2
投票

在没有适当的 TypeScript 背景的情况下,我能够编译以下内容(经过一些尝试和错误):

import {Request, Response} from "express";
interface Locals extends Record<string, any> {
  userId: number;
}
interface MyResponse extends Response {
  locals: Locals;
}
export function middleware(request: Request, response: MyResponse) {
  const {userId} = response.locals;
  response.end(userId);
  return userId;
}

声明文件 (

.d.ts
) 包含:

export declare function middleware(request: Request, response: MyResponse): number;

因此正确推断了

number
类型。

当我在

express
中使用这个中间件功能时它就可以工作。


0
投票

您可以查看我的新库express-typed,它是围绕 Express 路由器的小型安全打字稿包装器。

使用express-typed,返回的类型会从后端推断并导出,然后从前端导入。

成功部署到生产并改进了开发周期!

© www.soinside.com 2019 - 2024. All rights reserved.