我正在尝试从 Fastify 中的 JSON 模式实现类型推断。
文档中的示例对我不起作用,因为
request.query
仍然是unknown
或有时是{}
.
这里是 直接复制粘贴关于 stackblitz 的文档。如您所见,Typescript 编译失败。
任何想法?
Querystring
类型未定义因此错误。要定义它,请执行以下操作:
import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts';
import fastify from 'fastify';
const server = fastify().withTypeProvider<JsonSchemaToTsProvider>();
server.get<{ Querystring: { foo: number, bar: string } }>(
'/route',
{
schema: {
querystring: {
type: 'object',
properties: {
foo: { type: 'number' },
bar: { type: 'string' },
},
required: ['foo', 'bar'],
},
} as const, // don't forget to use const !
},
(request, reply) => {
const { foo, bar } = request.query; // type safe!
}
);
或者,为了保持干燥,安装
@sinclair/typebox
包并预先定义它,如:
import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts';
import fastify from 'fastify';
import { Static, Type } from '@sinclair/typebox';
const server = fastify().withTypeProvider<JsonSchemaToTsProvider>();
const getQuerystring = Type.Object({
foo: Type.Number(),
bar: Type.String(),
})
type GetQuerystring = Static<typeof getQuerystring>
server.get<{ Querystring: GetQuerystring }>(
'/route',
{
schema: {
querystring: getQuerystring,
} as const, // don't forget to use const !
},
(request, reply) => {
const { foo, bar } = request.query; // type safe!
}
);
这解决了问题(:
npm i json-schema-to-ts