eslint错误任意值上的不安全成员访问['content-type']

时间:2020-07-15 12:43:00

标签: javascript typescript eslint

以下代码产生了以下错误:

@ typescript-eslint / no-unsafe-member-access:任意值上的不安全成员访问['content-type']。

export const getGraphPhoto = async () => {
  try {
    const response = await getGraphDetails(
      config.resources.msGraphPhoto.uri,
      config.resources.msGraphPhoto.scopes,
      { responseType: 'arraybuffer' }
    )
    if (!(response && response.data)) {
      return ''
    }
    const imageBase64 = new Buffer(response.data, 'binary').toString('base64')
    return `data:${response.headers['content-type']};base64, ${imageBase64}`
  } catch (error) {
    throw new Error(`Failed retrieving the graph photo: ${error as string}`)
  }
}

承诺getGraphDetails返回Promise<AxiosResponse<any>>

问题显然是response.headers['content-type']对象上可能没有属性response。为了解决这个问题,我尝试先检查它,但是并不能消除警告:

    if (
      !(response && response.data && response.headers && response.headers['content-type'])
    ) { return '' }

感谢您提供的指导,可以帮助我更好地理解和解决此问题。

enter image description here

1 个答案:

答案 0 :(得分:1)

我已经有一段时间没有使用TypeScript了,所以我希望我不会犯任何错误...我认为该规则的目的不是要防止访问不存在的属性,而是要警告访问任何显式表示或隐式表示为any的对象的属性。如果有代码检查此属性是否存在,则该规则不考虑在内,而仅检查对象的类型。如果不是警告response.dataresponse.headers而是仅访问response. headers['content-type'],我猜是输入了getGraphDetails响应,而headers属性是{ {1}}。我认为您有三种选择:

  • 将类型设置为响应头。我不确定是否可以在现有项目中找到一个接口,但是如果找不到,则可以根据需要声明一个显式接口,并按如下方式使用它:
any
  • 禁用此行或整个文件的规则。

  • 忽略警告。