ZiiMakc
ZiiMakc

Reputation: 36786

Typescript is Type for object property

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

Answers (1)

Aleksey L.
Aleksey L.

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
}

Playground

Upvotes: 2

Related Questions