1

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

1 Answer 1

2

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
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.