1

I'm relatively new to Typescript and am already in love, but I'm facing a weird problem right now:

I create a string array in the parent component, pass it down to a child component as prop and try to access the array with a numbered index from there.

This is the compile error i get:

TypeScript error in /home/simon/development/portfolio/src/components/Projects/ImageSlider/ImageSlider.tsx(27,23): Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'PropsWithChildren'. Property '0' does not exist on type 'PropsWithChildren'. TS7053

ImageSlider.tsx (child)

import React, { useEffect, useState } from "react";
import styles from "./ImageSlider.module.scss";
import { motion } from "framer-motion";
import Modal from "react-modal";

interface ImageSliderProps {
    images: string[];
}

const ImageSlider: React.FC<ImageSliderProps> = (images) => {
 
    const [index, setIndex] = useState<number>(0);

    const slideRight = () => { };
    const slideLeft = () => { };

    return (
        <div className={styles.slider_wrapper}>
            <button></button>
            <img src={images[0]} alt="" />
            <button></button>
        </div>
    );
};

export default ImageSlider;

Parent Component:

...

  let sliderImages: string[] = [
    "../../assets/Dotrice/dotrice-background.png",
    "../../assets/Dotrice/dotrice1.png",
    "../../assets/Dotrice/dotrice2.png",
    "../../assets/Dotrice/dotrice3.png",
    "../../assets/Dotrice/dotrice4.png",
  ];

return (
    <ImageSlider images={sliderImages} />
);

... 

Do i have to explicitly set the type of the array index somewhere?

Thanks, have a great day and stay safe out there :)

1 Answer 1

2

images is a field inside props object. You can either use destructuring:

const ImageSlider: React.FC<ImageSliderProps> = ({ images }) => {

or refer to the props firstly:

const ImageSlider: React.FC<ImageSliderProps> = (props) => {

<img src={props.images[0]} alt="" />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.