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` })
}
}