javascript - TypeScript Fel: "Element har implicit typen 'any' eftersom uttryck av typen 'any' inte kan användas för att indexera typen"
[Hej!][1]
Jag får detta TypeScript-fel { "Element har implicit typen 'any' eftersom ett uttryck av typen 'any' inte kan användas för att indexera typen '{ 0: { image: string; title: string; text: string; }; 1: { image: string; title: string; text: string; }; 2: { image: string; title: string; text: string; }; }'.", }. TS7053
Osäker på var mina gränssnitt behöver läggas till eller om det alls krävs?
detta är markerat setCurrent(carouselData[event.target.getAttribute("data-Testimonials")])
vad jag ska ändra dem till. Jag har ingen aning om var jag gör fel, eftersom jag bara har programmerat i en månad.
Min kod för en karusell:
interface CarouselCardProperties {
image: string;
title: string;
text: string;
}
export default function Testimonials() {
const carouselData = {
0: {
image: tobi,
title: "I no longer have to howl at the moon to call for my lady !!",
text: "Tobi ~ Vancouver, Canada",
},
1: {
image: girly,
title: "With Enrico going on dates, we have more time to ourselves!",
text: " Gina ~ Rome, Italy",
},
2: {
image: loveshades,
title: "I no longer have to worry about staying clean, I kitties licking me every night. I have Love Shades on.",
text: " Princess ~ Georgia, USA",
},
};
const [current, setCurrent] = useState(carouselData[0])
const [active, setActive] = useState(0)
const handleSetClick = (event:any) => {
setCurrent(carouselData[event.target.getAttribute("data-Testimonials")])
setActive(event.target.getAttribute("data-Testimonials"))
};
return (
<Container>
<Img src={current.image} />
<Title>{current.title}</Title>
<Text>{current.text}</Text>
<div>
{Object.keys(carouselData).map(index => (
<Span
onClick={(event:any) => handleSetClick(event)}
data-Testimonials={index}
key={index} />
))}
</div>
</Container>
)
}```
[1]: https://i.sstatic.net/A9CwZ.png
Svar #1
Varför behöver du ett data-Testimonials-attribut?
Skicka bara direkt indexet till handleSetClick:
const handleSetClick = (index: keyof typeof carouselData) => {
setCurrent(carouselData[index])
setActive(index)
};
return (
<Container>
<Img src={current.image} />
<Title>{current.title}</Title>
<Text>{current.text}</Text>
<div>
{Object.keys(carouselData).map(index => (
<Span
onClick={() => handleSetClick(index)}
key={index} />
))}
</div>
</Container>
)
Svar #2
Koden
const carouselData = {
0: {
// ...
}
}
definierar carouselData-data för att använda numeriska index, men du indexerar det med event.target.getAttribute("data-Testimonials"), som implicit har typen any. Jag skulle starkt typa din event-parameter, så att event.target.getAttribute("data-Testimonials") har typen string. Jag skulle sedan omdefiniera carouselData för att använda strängindex på följande sätt:
const carouselData = {
'0': {
// ...
},
'1': {
// ...
}
}
Det är i allmänhet bäst att undvika any-typen när det är möjligt för att undvika den här typen av situationer.
