以下代码产生了以下错误:
@ 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 '' }
感谢您提供的指导,可以帮助我更好地理解和解决此问题。
答案 0 :(得分:1)
我已经有一段时间没有使用TypeScript了,所以我希望我不会犯任何错误...我认为该规则的目的不是要防止访问不存在的属性,而是要警告访问任何显式表示或隐式表示为any
的对象的属性。如果有代码检查此属性是否存在,则该规则不考虑在内,而仅检查对象的类型。如果不是警告response.data
或response.headers
而是仅访问response. headers['content-type']
,我猜是输入了getGraphDetails
响应,而headers
属性是{ {1}}。我认为您有三种选择:
any
禁用此行或整个文件的规则。
忽略警告。