Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
How to check object type from request.body in Typescript?

I need to check the object type from the request body and then run approbiate function based on this type, I try do this in this way:

export interface SomeBodyType {
    id: string,
    name: string,
    [etc....]
}

export const someFunction = async (req: Request, res: Response) => {
    const { body } = req.body;

    if (body instanceof SomeBodyType) {
        //run function A
    } else {
        // run function B
    }
}

but it not work, cause my SomeBodyType return me error: only refers to a type, but is being used as a value here.,

so, how can i check the type of the body in this case?

thanks for any help!

//// EDIT:

thanks to @phn answer I create this generic function to check object types:

export const checkObjectType = <T>(body: T): boolean => {
    return (body as T) !== undefined;
}

please, take a look and comment if this function is good

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As stated in the comments already, types don't exist in runtime.

You need to write a function to validate the content received in the body, one approach is from the TypeScript documentation (see code example).

A more advanced and dynamic approach is to use a validation library to validate your input against a schema or contract, for example ajv

interface SomeBodyType {
  id: string,
  name: string
}

function isBodyType(body: any): body is SomeBodyType {
  return (body as SomeBodyType).id !== undefined &&
    (body as SomeBodyType).name !== undefined;
}

export const someFunction = (req: Request, res: Response) => {
  const { body } = { body: { id: '', name: '' } };

  if (isBodyType(body)) {
    // run function A
  } else {
    // run function B
  }
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!