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

以下代码生成以下eslint错误:

对Any值的

@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.headers['content-type']。要解决此问题,我首先尝试检查它,但这并不能消除警告:

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

感谢您为我更好地了解和解决此问题提供的任何指导。


解决方案

我已经有一段时间没有使用打字稿了,所以我希望我没有犯任何错误...我认为该规则的目的不是为了阻止对不存在的属性的访问,而是警告任何对象(显式或隐式)对any的属性的访问。如果有代码检查此属性是否存在,则规则不会考虑,而只是考虑对象的类型。如果没有警告访问response.dataresponse.headers,而只是访问response. headers['content-type'],我猜getGraphDetails响应被类型化,但headers属性被类型化为any。我认为您有三个选择:

  • 将类型设置为响应头部。我不确定您是否可以在现有项目中找到一个接口,但如果不能,您可以根据需要声明一个显式接口,并按如下方式使用它:
interface ResponseHeaders {
  'content-type': string,
  [key: string]: string, // you could set more explicit headers names or even remove the above and set just this line
}
const headers : ResponseHeaders = response.headers;
  • 禁用此行或整个文件的规则。

  • 忽略该警告。

相关文章