在typescript中,我尝试从http请求头中获取属性。
属性是一个字符串(当然,它来自报头),我需要将其解析为Integer
export const getUser = async (req, _res, next) => {
const userId: number = parseInt(req.headers.userid);
... other code
}
但是,vs code IDE在req.headers.userid
下显示红线并抱怨:
(property) IncomingMessage.headers: IncomingHttpHeaders
Argument of type 'string | string[] | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2345)
我怎么做这个简单的任务?
该错误消息说您的变量键入string | string[] | undefined
,但parseInt
需要string
。所以你必须处理userid
可能的其他类型。
可能是这样的:
const userIdHeader = req.headers.userid
if (typeof userIdHeader === 'string') {
const userId = parseInt(userIdHeader);
}
现在你只能在你有一个字符串,并且typescript知道它的情况下才能访问到这些代码。
所以文档在缩小以获取更多信息。
我刚刚遇到了完全相同的问题,我解决了:
const userIdHeader = req.headers.userid;
const userId = parseInt(String(userIdHeader));
或更好:
const userId = parseInt(String(req.headers.userid));