Typescript-eslint - unsafe assignment of an 'any' value

const [currentIndex, setCurrentIndex] = useState(Math.floor((slidesLength / 2)))
const percent = (100 * (currentIndex + 1)) / slidesLength;

if (typeof window !== "undefined") {
window.addEventListener('storage', () => {
const index: number = JSON.parse(localStorage.getItem('currentIndex')!) ?? Math.floor((slidesLength / 2));
setCurrentIndex(index)
})
}
const [currentIndex, setCurrentIndex] = useState(Math.floor((slidesLength / 2)))
const percent = (100 * (currentIndex + 1)) / slidesLength;

if (typeof window !== "undefined") {
window.addEventListener('storage', () => {
const index: number = JSON.parse(localStorage.getItem('currentIndex')!) ?? Math.floor((slidesLength / 2));
setCurrentIndex(index)
})
}
This code cause this eslint error
--23:13 Error: Unsafe assignment of an `any` value. @typescript-eslint/no-unsafe-assignment
23:32 Warning: Forbidden non-null assertion. @typescript-eslint/no-non-null-assertion
--24:23 Error: Unsafe argument of type `any` assigned to a parameter of type `SetStateAction<number>`. @typescript-eslint/no-unsafe-argument
--33:28 Error: Invalid type "string | undefined" of template literal expression. @typescript-eslint/restrict-template-expressions
--23:13 Error: Unsafe assignment of an `any` value. @typescript-eslint/no-unsafe-assignment
23:32 Warning: Forbidden non-null assertion. @typescript-eslint/no-non-null-assertion
--24:23 Error: Unsafe argument of type `any` assigned to a parameter of type `SetStateAction<number>`. @typescript-eslint/no-unsafe-argument
--33:28 Error: Invalid type "string | undefined" of template literal expression. @typescript-eslint/restrict-template-expressions
2 Replies
Wolle
Wolle17mo ago
If I encoutered an "Unsafe assignment of an any value" it was often because a variable was not typed correctly. Maybe because of a typo in the type name, maybe because of missing/Wrong import.
Nikita
NikitaOP17mo ago
ChatGPT4 helped
if (typeof window !== "undefined") {
window.addEventListener('storage', () => {
const index: number = JSON.parse(localStorage.getItem('currentIndex') ?? '') as number;
setCurrentIndex(index ?? Math.floor(slidesLength / 2));
})
}
if (typeof window !== "undefined") {
window.addEventListener('storage', () => {
const index: number = JSON.parse(localStorage.getItem('currentIndex') ?? '') as number;
setCurrentIndex(index ?? Math.floor(slidesLength / 2));
})
}
Want results from more Discord servers?
Add your server