Reputation: 36786
Is it possible?
const isNotValidated = <T>(req: NextApiRequest, res, schema: any): req.body is T => {}
NextApiRequest cannot be changed:
declare type NextApiRequest = IncomingMessage & {
/**
* Object of `query` values from url
*/
query: {
[key: string]: string | string[];
};
/**
* Object of `cookies` from header
*/
cookies: {
[key: string]: string;
};
body: any;
};
Upvotes: 1
Views: 108
Reputation: 37918
There're no type guards for object properties, but you can define guard for whole object:
interface NextApiRequestEx<T> extends NextApiRequest {
body: T;
}
type Bar = { bar: string };
const isNotValidated = <T>(req: NextApiRequest): req is NextApiRequestEx<T> => true;
declare const req: NextApiRequest;
if (isNotValidated<Bar>(req)) {
req.body.bar // req.body is of type Bar here
}
Upvotes: 2