[英]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: 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;
};
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.