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; }'
Thanks in advance
CodePudding user response:
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>
);
}