Typescript是对象属性的Type

时间:2019-12-26 12:09:48

标签: typescript

有可能吗?

const isNotValidated = <T>(req: NextApiRequest, res, schema: any): req.body is T => {}

NextApiRequest不能更改:

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 个答案:

答案 0 :(得分:2)

没有用于对象属性的类型保护,但是您可以为整个对象定义保护:

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