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

Dar*_*te1 15 javascript typescript eslint

以下代码生成以下 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}`)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

    if (
      !(response && response.data && response.headers && response.headers['content-type'])
    ) { return '' }
Run Code Online (Sandbox Code Playgroud)

感谢您为我提供的任何指导,以便我更好地理解和解决这个问题。

在此输入图像描述

vir*_*ogm 5

我已经有一段时间没有使用 TypeScript了,所以我希望我不会犯任何错误...我认为该规则的目的不是阻止访问不存在的属性,而是警告访问不存在的属性任何对象的属性any(显式或隐式)。该规则不考虑是否有代码检查该属性是否存在,而仅考虑对象的类型。如果它不是关于访问response.data或 的警告,response.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;
Run Code Online (Sandbox Code Playgroud)
  • 禁用该行或整个文件的规则。

  • 忽略警告。

  • 很好的解释,谢谢。我想知道的一件事是为什么 TypeScript 本身没有被这个问题绊倒,而只有 linter 抱怨? (5认同)