eslint error Unsafe member access [#39;content-type#39;] on an any value(对任意值的eslint错误不安全成员访问[#39;content-type#39;])
问题描述
以下代码生成以下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.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;
禁用此行或整个文件的规则。
忽略该警告。
这篇关于对任意值的eslint错误不安全成员访问[';content-type';]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对任意值的eslint错误不安全成员访问[';content-type';]
基础教程推荐
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- 从快速中间件中排除路由 2022-01-01
