[英]Fastify Typescript: body unknown
这是我第一次使用 Fastify,我在尝试访问 Typescript 中正文中的值时遇到了问题。
有什么想法或建议吗? 谢谢!
更新:我想避免使用app.get(...)
等来简化代码
这是我的代码:
应用程序.ts
const buildServer = (options = {}) => {
const app = fastify(options);
app.register(routesApiV1, { prefix: '/api'});
return app;
}
路线.ts
const routesApiV1: FastifyPluginCallback = (fastify, options, done) => {
fastify.route(userRoute);
done();
}
用户.ts
const handler: RouteHandlerMethod = async (req, res) => {
const {
name,
lastName,
dateOfBirth,
addressLine,
zipCode,
city,
country
} = req.body; // Property '...' does not exist on type 'unknown'
...
}
const route: RouteOptions = {
method: 'GET',
url: '/user/:id',
// schema: fastifySchema, Tried but not working
handler,
preValidation,
}
FastifyRequest
类型是一个通用类型。 你应该通过它你的体型...
import type { FastifyRequest } from 'fastify'
interface BodyType {
name: string
}
const handler = async (req: FastifyRequest<{ Body: BodyType }>) => {
const { name } = req.body
}
当您使用RouteHandlerMethod
时,它默认将请求 object 输入为FastifyRequest<{ Body: unknown }>
,因此 body 的类型未知
您需要声明类型并键入RouteHandlerMethod
和RouteOptions
,如下所示:
type Body = {
name: string;
// ...
}
type Response = {
// ...
}
import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod } from "fastify";
const handler: RouteHandlerMethod<
RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
{ Reply: Response; Body: Body }
> = async (req, res) => {
const {
name,
lastName,
dateOfBirth,
addressLine,
zipCode,
city,
country
} = req.body; // Property '...' does not exist on type 'unknown'
...
}
import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod, RouteOptions } from "fastify";
const route: RouteOptions<RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
{ Reply: Response, Body: Body }> = {
method: 'GET',
url: '/user/:id',
// schema: fastifySchema, Tried but not working
handler,
preValidation,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.