对象可能是“未定义的”(Object is possibly 'undefined')

编程入门 行业动态 更新时间:2024-10-10 05:22:33
对象可能是“未定义的”(Object is possibly 'undefined')

所以我在vscode打字机2.5.3和下面的代码:

export function isHttpHeaders ( headers: HttpHeaders | undefined ): headers is HttpHeaders { return !!headers && !!headers.get && !!headers.set } function headersToHeadersSpec ( options?: RequestOptionsArgs ): Headers | undefined { const { headers } = options as RequestOptionsArgs if ( isHttpHeaders( headers ) ) { const reqHeaders = new Headers() headers.forEach( reqHeaders.set.bind( reqHeaders ) ) return reqHeaders } else { return undefined } }

当我尝试编译时,出于某种原因, headers.forEach( reqHeaders.set.bind( reqHeaders ) )抱怨头标值可能未定义。 警卫不应该保证这个值不是未定义的吗?

So I am in vscode on typescript 2.5.3 and the following code:

export function isHttpHeaders ( headers: HttpHeaders | undefined ): headers is HttpHeaders { return !!headers && !!headers.get && !!headers.set } function headersToHeadersSpec ( options?: RequestOptionsArgs ): Headers | undefined { const { headers } = options as RequestOptionsArgs if ( isHttpHeaders( headers ) ) { const reqHeaders = new Headers() headers.forEach( reqHeaders.set.bind( reqHeaders ) ) return reqHeaders } else { return undefined } }

When I attempt to compile, for some reason the line headers.forEach( reqHeaders.set.bind( reqHeaders ) ) is complaining that the headers value is possibly undefined. Shouldn't the type guard guarantee that the value is not undefined?

最满意答案

这个错误来自你定义的HttpHeaders ,它将forEach设置为一个可选成员。

要解决这个错误,只需标签 - 它是非可选的,通过删除? :

interface HttpHeaders { get?: string set?: string forEach (Function): void }

The error comes from your definition of HttpHeaders which sets forEach as an optional member.

To fix the error, just label-it non-optional by removing the ? :

interface HttpHeaders { get?: string set?: string forEach (Function): void }

更多推荐

本文发布于:2023-08-06 08:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1447639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   未定义   Object   possibly   undefined

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!