I am trying to create a chatbox with React using typescript and Firebase. This is my code for the Room and Message component:
function ChatRoom() {
const messagesRef = firestore.collection('messages');
const query = messagesRef.orderBy('createdAt').limit(25);
const [messages] = useCollectionData(query, { idField: 'id' });
console.log(messages);
return (
<>
{messages &&
messages.map(msg => <ChatMessage key={msg.id} message={msg} />)}
</>
);
}
function ChatMessage(props: any) {
const { text, uid, photoURL } = props.message;
return (
<>
<p>{text}</p>
</>
);
}
when I specify key={msg.id} it says that Object is of type 'unknown'. TS2571. I tried to create an interface for the Mesaage which is:
interface Message {
id: string;
text: string;
createdAt: { nanoseconds: number; seconds: number };
}
But I'm not able to understand how do I specify this Interface to the msg in the map function.
I tried:
{messages && messages.map(msg: Message => <ChatMessage key={msg.id} message={msg} />)}
but that didn't work too. I am new to TypeScript and React and any help would be appreciated. Much thanks.
{messages && messages.map((msg: Message) => <ChatMessage key={msg.id} message={msg} />)}Argument of type '(msg: Message) => JSX.Element' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => Element'. Types of parameters 'msg' and 'value' are incompatible. Type 'unknown' is not assignable to type 'Message'.message?Array(3) 0: createdAt: t {seconds: 1603996200, nanoseconds: 0} id: "LlyqGWDBmnQAGqdJjFwG" text: "Nope :(" __proto__: Object 1: {text: "plsss", createdAt: t, id: "gEtenzx09HLPUUzg4SRR"} 2: {text: "newwwww", createdAt: t, id: "WfLWpeU4dXTYCt0zdVEN"} length: 3 __proto__: Array(0)