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
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
}
};