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)
感谢您为我提供的任何指导,以便我更好地理解和解决这个问题。
我已经有一段时间没有使用 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)
禁用该行或整个文件的规则。
忽略警告。
归档时间: |
|
查看次数: |
64797 次 |
最近记录: |