gpt4 book ai didi

node.js - Express + TypeScript : Create type inference for response. 本地人

转载 作者:行者123 更新时间:2023-12-05 04:37:20 27 4
gpt4 key购买 nike

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

最佳答案

在没有适当的 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 中使用这个中间件功能时,它就起作用了。

关于node.js - Express + TypeScript : Create type inference for response. 本地人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70712879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com