简体   繁体   English

对象可能是“未定义”的

[英]Object is possibly 'undefined'

So I am in vscode on typescript 2.5.3 and the following code: 所以我在打字稿2.5.3和以下代码的vscode中:

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. 当我尝试编译时,出于某种原因,行headers.forEach( reqHeaders.set.bind( reqHeaders ) )抱怨标题值可能未定义。 Shouldn't the type guard guarantee that the value is not undefined? 类型防护程序不应该保证该值不是未定义的吗?

The error comes from your definition of HttpHeaders which sets forEach as an optional member. 该错误来自您对HttpHeaders的定义,该定义将forEach设置为可选成员。

To fix the error, just label-it non-optional by removing the ? 要解决该错误,只需通过删除?将其标记为非可选即可? :

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

Considering you have option? 考虑到您有option? which means the parameter is optional , it would allow options to be undefined. 这意味着参数是可选的 ,它将允许options未定义。 Even if you have code in other functions that check the value, typescript isn't smart enough to look at that code and figure out what it does. 即使您在其他函数中具有检查值的代码,打字稿也不够聪明,无法查看该代码并确定其作用。 Your code is not Compile-Time safe, but may be Run-Time safe. 您的代码不是编译时安全的,但可能是运行时安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM