skip to Main Content

Hi i am new to typescript and react, i need to pass a single TypeScript object as props in Child component, i found a similar question

how to pass TypeScript Interface Object array as props in React Child component
but here its trying to send a array of type script object, but I need to send a single object, i tried changing all array to single objects but its not working.

interface

export type IUserType = {
  id: number;
  name: string;
  username: string;
  email: string;
};

Parent.tsx

import { useEffect, useState } from "react";
import { IUserType } from "./ApiInterface";
import "./App.css";
import Child from "./Child";
export default function App() {
  const [user, setUser] = useState<IUserType>();

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/users/1`)
      .then((res) => res.json())
      .then((res) => setUser(res as IUserType));
  }, []);
  return (
    <>
      <Child user={user} />
    </>
  );
}

Child.tsx

import { IUserType } from "./ApiInterface";

const Child: React.FunctionComponent<IUserType> = (user): JSX.Element => {
  return <div>{JSON.stringify(user)}</div>;
};
export default Child;

error

ERROR in src/App.tsx:23:14
TS2322: Type '{ user: IUserType | undefined; }' is not assignable to type 'IntrinsicAttributes & IUserType'.
  Property 'user' does not exist on type 'IntrinsicAttributes & IUserType'.
    21 |         }}
    22 |       />
  > 23 |       <Child user={user} />
       |              ^^^^
    24 |     </>
    25 |   );
    26 | }

2

Answers


  1. Pls. check prop type for your child component. While defining typescript props for child component, it expects a JS object, with each prop described as mentioned in IChildProps below.

    import { IUserType } from "./ApiInterface";
    interface IChildProps {
      user: IUser;
    }
    const Child: React.FunctionComponent<IChildProps> = ({user}): JSX.Element => {
      return <div>{JSON.stringify(user)}</div>;
    };
    export default Child;
    
    Login or Signup to reply.
  2. In TypeScript, interfaces are used to define the structure and behavior of objects. They are a compile-time construct and exist only during the development and build process. Once the code is transpiled to JavaScript and executed at runtime, interfaces are not available.

    When working with React components and props, it’s important to understand that props are essentially a way to pass data from a parent component to a child component. Props are passed as runtime values and are not part of the build-time type checking. Therefore, you cannot directly pass an interface as a prop from a parent component to a child component.You can use generics though.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search