对象可能是“未定义的”(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 }更多推荐
发布评论