Home > Back-end >  How to fix problem when trying to type an object in typescript?
How to fix problem when trying to type an object in typescript?

Time:02-20

I need to type data returned from a request. One of these data returns the address object. If I type by putting "address: object", the typescript marks an error not recognizing the state and city that are inside the object. How can I fix this problem?

Code:

  import axios from "axios"
import { useEffect, useState } from "react"
import { baseURL } from "../../constants/url"
import { Container, Content, Discription, ImgContainer, ProductCard, Separator } from "./styles"

interface ProductType {
    product_name: string
    address: object
    discription: string
    image: string
}


export const Product = () => {
    const [products, setProducts] = useState<ProductType[]>([])


    useEffect(() => {
        axios.get(`${baseURL}`)
            .then(response => setProducts(response.data))
    }, [])


    return (
        <Container>
            {products.map((product) => {
                return (
                    
                    <ProductCard>
                        <ImgContainer>
                            <img src={product.image} alt="" />
                        </ImgContainer>

                        <Content>
                            <h4>
                                <strong>{product.product_name}</strong>
                            </h4>
                            <p>{product.address.state}, {product.address.city}</p>
                        </Content>

                        <Separator />

                        <Discription>
                            <p>{product.discription}!</p>
                        </Discription>
                    </ProductCard>
                )
            })}
        </Container>
    )
}

CodePudding user response:

address: object is not precise enough. If the address object actually has city and state properties, you should note those in the type definition.

interface ProductType {
    product_name: string
    address: {
        city: string
        state: string
    }
    discription: string
    image: string
}

I'd also highly recommending fixing the discription typo, both in the front-end here and in the API - typos are a frequent source of problems in programming.

axios.get(`${baseURL}`) also simplifies to axios.get(baseURL).

You should also indicate to axios that you're expecting the response to be of type ProductType[].

axios.get<ProductType[]>(baseURL)

CodePudding user response:

This should do the trick for you :

interface Address {
  state: string;
  city: string;
}

interface ProductType {
  product_name: string;
  address: Address;
  discription: string;
  image: string;
}
  • Related