[英]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.