Encountering issues with Typescript when providing parameters for res.status().json()

I've recently started using Typescript and I'm still in the learning process by converting some existing JS code to TS. In my code:

res.status(200).json({ user: data.user })

I encountered a red squiggly underline under user:data.user with the following error:

Argument of type '{ user: any; }' is not assignable to parameter of type 'Data'. Object literal may only specify known properties, and 'user' does not exist in type 'Data'.ts(2345)

The same issue occurred with another line of code that uses res.status().json:

res.status(data.error.status).json({
                    message: msgString.toString(),
                })

Here's the related error:

Argument of type '{ message: any; }' is not assignable to parameter of type 'Data'. Object literal may only specify known properties, and 'message' does not exist in type 'Data'.ts(2345)

I need help converting these lines properly to Typescript to eliminate these errors and warnings.

Below is the complete code snippet:

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

import { API_URL } from '@/config/index'
import cookie from 'cookie'

type Data = {
    name: string
}

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse<Data>
) {
    // res.status(200).json({ name: 'SIGN UP' })

    if (req.method === 'POST') {
        console.log('POST POST POST')
        const { username, email, password } = req.body

        console.log('/api/login.js')
        console.log(req.body)

        const strapiRes = await fetch(`${API_URL}/api/auth/local/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username,
                email,
                password,
            }),
        })

        const data = await strapiRes.json()

        console.log('data', data)

        if (strapiRes.ok) {
            console.log('strapiRes.ok')
            // @todo - Set cookie

            //Set cookie
            res.setHeader(
                'Set-Cookie',
                cookie.serialize('token', data.jwt, {
                    httpOnly: true,
                    secure: process.env.NODE_ENV !== 'development',
                    maxAge: 60 * 60 * 24 * 7, // a week
                    sameSite: 'strict',
                    path: '/',
                })
            )
            res.status(200).json({ user: data.user })
        } else {
            console.log('else of strapiRes.ok')

            console.log('errors', data.error.details)

            if (data.error.details.errors) {
                console.log('x', data.error.details.errors)

                var msgString = data.error.details.errors.map((x) => {
                    console.log('x', x)

                    return x.message
                })

                console.log('msgString', msgString)
                res.status(data.error.status).json({
                    message: msgString.toString(),
                })
            } else {
                res.status(data.error.status).json({
                    message: data.error.message,
                })
            }
        }
    } else {
        res.setHeader('Allow', ['POST'])
        res.status(405).json({ message: `Method ${req.method} not allowed` })
    }
}

Answer №1

interface Info = {
    content?: string
    person?: any
}

rather than simply

interface Info = {
    title: string
}

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

Unsynchronized state of affairs in the context of Angular navigation

Within my Angular project, I am currently relying on an asynchronous function called foo(): Promise<boolean>. Depending on the result of this function, I need to decide whether to display component Foo or Bar. Considering my specific need, what woul ...

Issue TS1112: It is not possible to declare a class member as optional

I'm currently working on creating a movie catalog using Angular and Ionic. Within the Movie class, I have properties for id, title, image, and plot. On the initial page of the app, only the id, title, and image are displayed, while the plot is omitte ...

TypeScript Generic Functions and Type Literals

Everything seems to be running smoothly: type fun = (uid: string) => string const abc: fun = value => value const efg = (callback:fun, value:string) =>callback(value) console.log(efg(abc, "123")) However, when we try to make it generic, we e ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

Image missing aria-label attribute

I am facing an issue with getting the aria-label to display on my image. Despite checking my code, I cannot figure out why it is not working. Any ideas on what might be missing? Here is the code from my NextJS app: The svg in my public folder. <?xml v ...

The argument type 'string' does not match the parameter type 'keyof Chainable' in Cypress JavaScript

Trying to incorporate a unique custom command in Cypress (commands.js file) as follows: Cypress.Commands.add("login", (email, password) => { cy.intercept('POST', '**/auth').as('login'); cy.visit(& ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

Keys preset in TypeScript using keyof

I need a set of predefined keys, but users should not be restricted to only using those keys. type B = { a: string; b: number; } type T = keyof B | string; function someFunc(key: T) {} someFunc(); // key type is `T` In the scenario above, I am lo ...

Transforming a non-specific type into a container permits precarious assignments

I'm encountering an issue with the code snippet provided below. Despite having a specific type where Type<boolean> cannot be assigned to Type<true>, when wrapping it in an object type (BoxType as shown), suddenly BoxType<boolean> wro ...

Is your Angular app missing i18next translations?

Can Angular's i18next provider be configured to hide any value when the key is not defined? The issue arises when there is no translation defined for a specific key like my:key. I want to display an empty string in the template instead of showing the ...

Troubleshooting the 'npm ERR! ERESOLVE could not resolve' and 'peer dependency' issues: A guide to fixing the ERESOLVE error in npm

After several days of encountering an error while trying to set up a website for remote training, I have not been able to find a solution that fits my needs. Requesting your help to resolve the issue and get the site live on Vercel. Thank you in advance f ...

Accessing JSON data stored locally and initializing it into a TypeScript variable within a React application

I'm new to working with JSON arrays and I'm facing a challenge. I am looking for a way to load data from a JSON file into a Typescript variable so that I can perform a specific operation that involves arrays. However, I'm unsure of how to ac ...

Styling components with SASS in NextJS

I've encountered an issue while working on a basic NextJS app, specifically with component-level styling using SASS/SCSS. Initially, everything appears fine when the user lands on the page for the first time. However, as they navigate to different pag ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

Transmitting confidential information to the Next.js Link module

One aspect I'm curious about is the Link component from 'next-Link'. If I need to pass sensitive data, such as a category_id, how can I securely transmit it for use in the getServerSideProps() function without relying on query strings? ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

Encountering a Next.js error when attempting to execute code on a live server

Encountering a frustrating error: Failed to compile ./utils/styles.js Error: failed to process internal error: entered unreachable code: assign property in object literal is invalid This annoying error popped up during the build process and can only be res ...

Angular 6: The Promise<any> is incompatible with the LeagueTable type

Recently delving into Angular and attempting to retrieve JSON League Table data from the API, I encountered an error message stating Type 'Promise' is not assignable to type 'LeagueTable'. leaguetable.service.ts import { Injectable } ...