Home > other >  Type 'string' is not assignable to type 'Message' in NEXT.JS (typescript)
Type 'string' is not assignable to type 'Message' in NEXT.JS (typescript)

Time:02-02

I am trying to create a clone of messenger using Next.Js as practice and while using typedefinitions and using "upstash, Serverless access to Redis database". I followed the entire procedure through documentation given by both NEXT.Js and Upstash Console using Node.js(already given on console of upstash). My typeDefinitions for a Message is as following: (typings.d.ts)

export type Message = {
    id: string,
    message: string,
    created_at: number,
    username: string,
    profilePic: string,
    email: string,
  };

Now in order to "addMessages" i have used api handling procedure (async promise) and created the following:

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
import redis from '../../redis';
import { Message }  from '../../typings';

type Data = {
    message: Message;
}

type ErrorData = {
    body: string
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data | ErrorData>
) {
    if(req.method != 'POST') {
        res.status(405).json({ body: "Method Not Allowed"
    });
    return;
    }

    const  { message }  = req.body;

    const newMessage = {
        ...message,
        //Replace the timestamp of the user to the timestamp of the server
        created_at: Date.now(),
    };
    // Push to upstash redis db

    await redis.hset("messages", message.id, JSON.stringify(newMessage));

  res.status(200).json({ message: "newMessage" })
}

on "type Data={ message: Message;}" and on last line of the code " res.status(200).json({ message: "newMessage" })"

as soon as i hit save it gives the following error : Type 'string' is not assignable to type 'Message'. I have tried hard reload, but the error remains there. Following this error as i hit a random message on Frontend, the console gave the following error: '"A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received"' I have already checked the console of upstash please help me out. Thank you.

CodePudding user response:

Thats because your Data interface requires an object with message as key and Message interface as value. Instead you are trying to send a string newMessage.

So you can do 3 things:

  1. I see you have a newMessage object, so instead of sending the string "newMessage", send the newMessage object, like so:
res.status(200).json({ message: newMessage });
  1. set the type of Data as
type Data=Message

This way you can send the message as

res.status(200).json({ message: "newMessage" });
  1. send the message in a nested key value pair
res.status(200).json({ message: {message: "newMessage" });

I would recommend the first one or the second one.

Also, typescript might complain that other fields from the Message interface are missing if you choose to send just a string. I would recommend that you make them optional.

  • Related