【问题标题】:Express + TypeScript: Create type inference for response.localsExpress + TypeScript:为 response.locals 创建类型推断
【发布时间】:2022-01-26 23:38:39
【问题描述】:

我想为我的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"

【问题讨论】:

  • 这对您有帮助吗? stackoverflow.com/a/49130179/5493813
  • @st.huber 不,不是真的:/。我正在寻找一种通过附加声明文件扩展 response.locals 的方法。
  • typeRoots 选项has a default value;确保包含它
  • 您是否尝试将其包含在 tsconfig 的 files 部分?
  • @ShamPooSham 是的,我试图将它包含在其中。不幸的是,没有改变任何东西。

标签: node.js typescript express


【解决方案1】:

在没有适当的 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 中使用这个中间件函数时它可以工作。

【讨论】:

  • userId 仍被 TypeScript 假定为 any。是的,它编译。但我并没有以这种方式实现类型安全。
  • 我已经编辑了我的答案。
猜你喜欢
  • 2018-07-03
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2016-04-04
  • 2017-03-08
相关资源
最近更新 更多