Skip to content
Advertisement

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

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement