【发布时间】: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