【问题标题】:eslint error Unsafe member access ['content-type'] on an any valueeslint 错误不安全的成员访问 ['content-type'] 对任何值
【发布时间】:2020-11-04 23:12:20
【问题描述】:

下面的代码会产生以下 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 '' }

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

【问题讨论】:

  • 这些错误只是被记录下来,不是吗?我的意思是,它们不会阻止阻止您的应用程序运行的错误
  • 没错

标签: javascript typescript eslint


【解决方案1】:

我有一段时间没有使用 TypeScript,所以我希望我不会犯任何错误......我认为该规则的目的不是阻止对不存在的属性的访问,而是警告访问任何以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;
  • 禁用此行或整个文件的规则。

  • 忽略警告。

【讨论】:

  • 很好的解释,谢谢。我想知道的一件事是为什么 TypeScript 本身没有绊倒,只有 linter 抱怨?
猜你喜欢
  • 2023-02-18
  • 2023-02-18
  • 2020-12-22
  • 2021-12-23
  • 2021-09-29
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多