[¡Hola!][1]
Recibo este error de TypeScript { "El elemento tiene implícitamente un tipo 'cualquiera' porque la expresión de tipo 'cualquiera' no se puede usar para indexar el tipo '{ 0: { imagen: cadena; título: cadena; texto: cadena; } ; 1: { imagen: cadena; título: cadena; texto: cadena; }; 2: { imagen: cadena; título: cadena; texto: cadena; }; }'.", }. TS7053
¿No está seguro de dónde se deben agregar mis interfaces o si es necesario?
esto está resaltado setCurrent(carouselData[event.target.getAttribute("data-Testimonios")])
a qué cambiarlos. No tengo idea de dónde me estoy equivocando, ya que solo he estado codificando durante un mes.
Mi código para un carrusel :
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.stack.imgur.com/A9CwZ.png¿Por qué necesita un atributo data-Testimonials ?
Simplemente pase directamente el índice a 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> )El código
const carouselData = { 0: { // ... } } define los datos de carouselData para usar índices numéricos, pero los indexa con event.target.getAttribute("data-Testimonials") , que implícitamente tiene cualquier tipo. Escribiría fuertemente su parámetro de event , por lo que event.target.getAttribute("data-Testimonials") tiene un tipo de cadena. Luego redefiniría carouselData para usar índices de cadenas así:
const carouselData = { '0': { // ... }, '1': { // ... } } En general, es mejor evitar any tipo siempre que sea posible para evitar este tipo de situaciones.