The data type 'string' cannot be assigned to the type 'Message' in NEXT.JS when using TypeScript

Currently, I am undertaking the task of replicating Messenger using Next.Js for practice. Throughout this process, I have integrated type definitions and incorporated "Upstash, Serverless access to the Redis database" as part of my project. I meticulously followed the guidelines provided by both NEXT.Js and Upstash Console, leveraging Node.js as directed on the Upstash console. The structure of my typeDefinitions for a Message object is outlined in the following snippet: (typings.d.ts)

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

To facilitate the addition of messages, I implemented an API handling procedure with asynchronous promises. The code snippet below illustrates this implementation:

// 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 with the server's timestamp
        created_at: Date.now(),
    };
    // Push to Upstash Redis DB

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

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

The error message indicating 'Type 'string' is not assignable to type 'Message'' and subsequent issues encountered upon saving the code are perplexing. Despite attempting a hard reload, the error persists. Upon interacting with the frontend interface, an additional error emerged: '"A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received"'. I have diligently reviewed the Upstash console but remain unable to resolve these challenges. Any assistance would be greatly appreciated. Thank you.

Answer №1

The reason for the error is that your Data interface expects an object with message as a key and the Message interface as the value. However, you are attempting to pass a string newMessage.

Here are three solutions:

  1. Since you already have a newMessage object, instead of sending the string "newMessage", send the newMessage object like this:
res.status(200).json({ message: newMessage });
  1. Change the type of Data to
type Data=Message

This will allow you to send the message like this

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

I suggest opting for the first or second solution.

Additionally, TypeScript may raise errors about missing fields from the Message interface if you choose to send only a string. It's best to make them optional to avoid this issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

Snippets of the webpage peeking through before the Fakeloader takes over

After implementing fakeloader to preload my content here, I have noticed that my site header often appears before the fakeloader preload animation completes. Is there a way to delay showing the content until the fakeloader is finished loading? Here is the ...

steps to initiate re-render of rating module

My first experience with React has been interesting. I decided to challenge myself by creating a 5-star rating component. All logs are showing up properly, but there seems to be an issue with the component not re-rendering when the state changes. Thank you ...

Set up an event listener for a specific class within the cells of a table

After spending the last couple of days immersed in various web development resources, I find myself stuck on a particular issue. As someone new to this field, the learning curve is quite steep... Let's take a look at a single row in my project: < ...

What is the minimum required node.js version for my project to run?

Is there a command in NPM that can display the minimum required Node version based on the project's modules? ...

"Creating a dynamic Map using the HERE Maps API and adjusting its size: A step-by-step guide

I am currently working on a Website project and I am interested in incorporating an interactive map from HERE Maps that spans the entire screen under my navigation bar. How can I achieve this? After initially using Google Maps, I switched to HERE Maps due ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

Clear out a collection in backbone.js

I am looking to clear out a collection by removing each item in sequence. this.nodes.each(function(node){ this.nodes.remove(node); }, this); The current method is ineffective as the collection length changes with each removal. Utilizing a temporary arr ...

Not every time you call the AngularJS run method does it actually execute

Working on a simple Angular app, I wanted to implement a user login check and redirection. However, I encountered an issue where accessing the home page from the form site resulted in inconsistent behavior - sometimes redirecting and other times showing ...

Implementing a Scroll Bar within a Stack Component in Material UI

I've developed a component and now I'm looking to enable scrolling when it expands beyond the screen width <Stack direction="row"> <Stack gap={1} overflow="auto"> {fields.map((el, i) => ( ...

What causes the index link to break when react-router's setRouteLeaveHook is used?

Issue: Whenever I include router.setRouteLeaveHook() or router.listenBefore() in my component, it causes the logo homepage Link to path="/" to break Scenario: I am attempting to implement a confirmation prompt before leaving a section. Below is the code f ...

Redirecting after executing JavaScript code

Is it possible to implement a redirect after the subscription script for push notifications has been executed successfully? <script> var OneSignal = window.OneSignal || []; OneSignal.push(function() { OneSignal.init({ ...

What methods can a Java application use to distinguish one browser from another?

Is there a way to determine if the browser being used is Firefox or Chrome? I am looking to create an application that will only run on a specific browser registered by a user. To achieve this, my application needs to be able to identify which browser the ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Adjust mouse coordinates to be relative to the coordinates of the <canvas> element

I'm currently facing the challenge of determining the exact location of the mouse on a canvas grid while still maintaining resizability. As of now, I have the mouse coordinates based on its position on the screen (x and y). The issue arises from the ...

Ensure to include Express validator version 6.4.0 in conjunction with express upload to verify the input data before proceeding with a POST request on the specified

Currently, I am facing a challenge in validating inputs, including an image upload, using express-validator and express-upload to parse multipart data. My goal is to validate the file being uploaded as an image or allow for no image upload. Despite followi ...

Issue with NodeJS Express's reverse proxy due to an invalid TLS certificate alternative name

I have configured a reverse proxy on my endpoint as shown below: var express = require('express'); var app = express(); var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); var serverOne = 'https://i ...

Complete a form when a link or button on the webpage is clicked

I have a variety of links and buttons on my webpage, and they are generated dynamically. I am unable to assign an onclick event to each one individually. My goal is to submit form data to the next page whenever any link or button on the page is clicked. ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...