Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  190] [ 6]  / answers: 1 / hits: 46451  / 4 Years ago, wed, july 15, 2020, 12:00:00

The following eslint errors are generated by the code below :



@typescript-eslint/no-unsafe-member-access: Unsafe member access ['content-type'] on an any value.



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}`)
}
}

The promise getGraphDetails returns Promise<AxiosResponse<any>>


The issue is clearly that the property response.headers['content-type'] might not be present on the response object. To fix this I tried checking for it first but that doesn't get rid of the warning:


    if (
!(response && response.data && response.headers && response.headers['content-type'])
) { return '' }

Thank you for any guidance you can give me to better understand and solve this issue.


enter


More From » typescript

 Answers
53

I haven't used TypeScript in a while so I hope I don't make any mistakes... I think that the intention of the rule is not to prevent access to a property that does not exist but to warn of the access to a property of any object typified as any (explicitly or implicitly). The rule doesn't take into account if there is code checking that this property exists but simply the type of the object. If it is not warning about accessing to response.data or response.headers but only to response. headers['content-type'], I guess that getGraphDetails response is typed but headers property is typed as any. I think you have three options:



  • Set the type to the response headers. I'm not sure if you could find one in an existing project but, if not, you could declare an Interface as explicit as you want to fit your needs and use it like this:


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;


  • Disable the rule for this line or the entire file.



  • Ignore the warning.




[#50794] Thursday, July 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;