javascript - res.body 的 TypeScript 类型注解

标签 javascript node.js typescript express

我正在为我的应用 node.js express 使用 typescript 。 我想说 res.body 是 personne 类型。 我试过这个:

router.post('/',(req: Request, res: Response) => {
   const defunt:PersoneModel = res.(<PersoneModel>body);
}

我有这个模型:

export type PersoneModel = mongoose.Document & {
  nom: String,
  prenom: String,
}

你能帮帮我吗?

谢谢。

最佳答案

更新:

@types/express@4.17.2 开始,Request 类型使用泛型。

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/index.d.ts#L107

interface Request<P extends core.Params = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }

您可以像这样将 req.body 的类型设置为 PersoneModel:

import { Request, Response } from 'express';

router.post('/',(req: Request<{}, {}, PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

对于@types/express@4.17.1及以下

遇到类似的问题,我用泛型解决了:

import { Request, Response } from 'express';

interface PersoneModel extends mongoose.Document {
  nom: String,
  prenom: String,
}

interface CustomRequest<T> extends Request {
  body: T
}

router.post('/',(req: CustomRequest<PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

关于javascript - res.body 的 TypeScript 类型注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48027563/

相关文章:

javascript - jQuery.on() 自己和 child

javascript - scrollTop() !== 不起作用

javascript - Angular/Typescript:从setTimeout函数内部调用函数

javascript - 如何使用 ngFor 使 json 数组中的数组动态化?

generics - Typescript TSX 和通用参数

javascript - node.js 使用 Passport 登录

javascript - Node.js包含JS文件并设置变量

node.js - 错误!此包已标记为私有(private)

javascript - 文件更改时 Webpack 开发服务器不会重新编译

javascript - 错误 : Route. put() 需要回调函数,但得到了 [对象未定义]