Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router with typescript how to import intrinsic attributes

First time using Typescript, I'm rendering a component inside of a map like this:

interface chatInterface {
  sender: string;
  avatar: string;
  content: string;
  time: string;
}
<>    
  {eachUser?.chats.map((item) =>
                  item.messages.map((obj: chatInterface, index: number) => {
                    return <ChatPage key={index} message={obj} />;
                  })
                )}
</>

And the ChatPage component is this:

function ChatPage(props: { message: chatInterface }) {
  const { sender, avatar, content, time } = props.message;
  return (
      <div>
        <ul>
          <li>
            <strong>{sender}:</strong> {content} at:{time}
          </li>
        </ul>
    </div>
  );
}

And it's working fine, but i want to create a page for the ChatPage component, but i don't know how i should import it in the react router. This is my app.tsx component:

<Router>
        <Navbar />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/profile" element={<Profile />} />
          <Route path="/chat" element={<ChatPage />} />
        </Routes>
      </Router>

It says that:

Property 'message' is missing in type '{}' but required in type '{ message: chatInterface; }'
like image 834
José Carlos Avatar asked Dec 05 '25 10:12

José Carlos


1 Answers

It looks like the ChatPage component is missing a better type declaration. The error is saying that the message prop is required and missing. In other words, it isn't an optional prop.

Make message an optional property and handle the destructuring fallback value in the component.

Example:

interface chatPageInterface {
  message?: chatInterface;
}

function ChatPage(props: chatPageInterface) {
  const { sender, avatar, content, time } = props.message || {};
  return (
      <div>
        <ul>
          <li>
            <strong>{sender}:</strong> {content} at:{time}
          </li>
        </ul>
    </div>
  );
}
like image 193
Drew Reese Avatar answered Dec 08 '25 00:12

Drew Reese