1

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.

4
  • {messages && messages.map((msg: Message) => <ChatMessage key={msg.id} message={msg} />)} Commented Nov 3, 2020 at 15:22
  • gives this error: 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'. Commented Nov 3, 2020 at 15:26
  • what is the value of message ? Commented Nov 3, 2020 at 15:27
  • console log of messages array gives thisArray(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) Commented Nov 3, 2020 at 15:30

2 Answers 2

2

Use your interface and type assertion whithin your map function

messages.map(msg => key = {(msg as ChatMessage).id} message = {msg})
Sign up to request clarification or add additional context in comments.

Comments

0

I had same issue with Typescript and react-query, same error Object is of type 'unknown'.

Installing this devDependency "@types/react-query" helped me somehow. I am using VS Code editor and I think that helped with type suggestions.

npm i --save-dev @types/react-query

Comments

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.