Fastify json-schema-to-ts 类型提供程序不起作用

问题描述 投票:0回答:2

我正在尝试从 Fastify 中的 JSON 模式实现类型推断。

文档中的示例对我不起作用,因为

request.query
仍然是
unknown
或有时是
{}
.

这里是 直接复制粘贴关于 stackblitz 的文档。如您所见,Typescript 编译失败。

任何想法?

node.js typescript fastify
2个回答
1
投票

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!
  }
);

0
投票

这解决了问题(:

npm i json-schema-to-ts
© www.soinside.com 2019 - 2024. All rights reserved.