0

I am new to typescript and can't seem to figure out the issue. I have created an interface and checking the props. its is working if props is empty but I am expecting a string and if number is passed it is not giving any error.

type Props = {
  name: number;
};

const ProductListItem = ({ name }: Props): JSX.Element => {
  return (
    <div className="product">
      <h4>{name}</h4>
    </div>
  );
};

export default ProductListItem;

Using the Component here like this

    import "./ProductList.scss";
import ProductListItem from "./ProductListItem";

interface Product {
  _id: string;
  itemName: string;
}
type Props = {
  allProducts: Array<Product>;
};

const ProductList = ({ allProducts }: Props): JSX.Element => {
  console.log(allProducts);
  const productsTodisplay = allProducts.map((product: any) => (
    <ProductListItem key={product._id} title={product.itemName} />
  ));
  return <section className="productsContainer">{productsTodisplay}</section>;
};

export default ProductList;
4
  • Could you provide where you import your ProductListItem? and how do you test the prop types? Commented Sep 4, 2021 at 5:03
  • I am not checking the propTypes, I thought If I set the type in the interface and pass some other value it would throw error? Commented Sep 4, 2021 at 5:12
  • 1
    Try my answer, if it throws errors. It should be if you not giving any props or wrong prop types. Commented Sep 4, 2021 at 5:16
  • Which code editor are you trying this on? Commented Sep 4, 2021 at 5:22

1 Answer 1

1

For a proper type checking in React Functional Component you could add its type to generic type parameter

Something like this:

import React, { FunctionComponent } from "react";

type Props = {
  name: number;
};

const ProductListItem: FunctionComponent<Props> = ({ name }) => {
  return (
    <div className="product">
      <h4>{name}</h4>
    </div>
  );
};

export default ProductListItem;
Sign up to request clarification or add additional context in comments.

3 Comments

Does it help? @special3220?
Yes, This approach also works. Also, I found what was wrong with my code, when I was mapping over all the products I set (product: any). When I removed it, it started working
Super! You could consider marking this accept if it is helpful for you and others who find this.

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.