Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda