Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Type a request parameter with express server

How do I Type (typescript) the attached post request to fix the error? I want to get the request body, but I can’t type it properly.

Thanks!

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import express = require('express');
import { Request } from 'express';
import bodyParser from 'body-parser';
import { parseBMI, calculateBMI } from './bmiCalculator';
import { calculateExercises } from './exerciseCalculator';

const app = express();
app.use(bodyParser.json());

app.get('/hello', (_,res) => {
  res.send("Good day");
});

app.get('/bmi', (req,res) => {
  const weight = Number(req.query.weight);
  const height = Number(req.query.height);
  console.log(weight,height);
  try {
    const {parseHeight, parseWeight} = parseBMI(height,weight);
    const out: string = calculateBMI(parseHeight,parseWeight);
    res.json({
      weight:parseWeight,
      height:parseHeight,
      bmi:out
    });
  } catch (e) {
    res.status(4004).json(e);
  }

});
app.post('/exercises',(req: Request<Array<number>,number>,res) => {
    const body:any = req.body;
    const dailyExercises = body.daily_exercises as Array<number>;
    const target = Number(body.target);

    res.json(calculateExercises(dailyExercises,target));
  });

const PORT = 3003;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

this is only concerning the /exercises route which throws error with eslint plugin on vscode

>Solution :

You will want to define an interface for your request:

interface Exercise {
    dailyExercises: number[],
    target: number
}

const exercise = req.body as Exercise

By then casting your req.body to an Exercise, you have an exercise constant that is strictly typed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading