TypeScript interface object coming from data fetching

Viewed 303

I'm new in TypeScript and I'm desperate, need help after spent all day trying to figure about interfaces, I looked all over internet and I'm not able to render a data fetched, because of the of interface typeError.

Here is my code:

export interface GalleryTest {
  x: {
    topTitle: string
    id: number
    imageCover: {
      path: string
    }
  }
  i: number
}

const ImageGallery = () => {
  //const [result, setResult] = useState<string[]>([])
  const arr: any = []
  const { exhibitor } = useParams<{ exhibitor: string }>()
  const { data } = useQuery('Collections', api.getData)
  data &&
    data.map((y: any, Firmennamen: string) => {
      if (exhibitor === y.Firmennamen) {
        y.Portfolio &&
          y.Portfolio.map((ele: any, i: number) => {
            ele.value.id = i + 1
            console.log(typeof ele.value)
            arr.push(ele.value)
            //setResult([...result, ele.value])
          })
      }
    })
  console.log(arr)
  return (
    <Gallery>
      {arr.map(({ x, i }: GalleryTest) => (
        <Link key={i} to='page/testId'>
          <div
            style={{
              backgroundImage: `url('https://source.unsplash.com/random')`,
              width: '25vw',
              height: 'auto',
              backgroundRepeat: 'no-repeat',
              backgroundSize: 'cover',
              backgroundPosition: 'center'
            }}
            className='flex-1 block min-h-0 last:mr-1 cursor-pointer rounded-xl drop-shadow-xl filter scroll-align-start scroll-px-9'
          >
            <div className='flex flex-col px-5 pt-24 pb-4'>
              <div className='text-white'>
                {x.topTitle} Smart Logistics Solutions
              </div>
              <p className='text-white font-thin text-xs pb-2'>
                Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna
                aliquyam
              </p>
            </div>
          </div>
        </Link>
      ))}
    </Gallery>
  )
}

And the eror is: TypeError: Cannot read property 'topTitle' of undefined

topTitle is define in the interface GalleryTest.

here is the data fecthed: enter image description here

1 Answers

This error doesn't relate to TypeScript. It's actually a JavaScript error. The problem is x is undefined. You need to assign it somehow.

One reason (there may be others) it's undefined is because of the map function signature. Replace { x, i } with x, i (unless GalleryTest is an object with a field called x?)

arr.map(( x: GalleryTest, i: number) => (...
Related