Skip to content

Usage of RouteShorthandOptions breaks type safety #186

@leosuncin

Description

@leosuncin

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.0.0

Plugin version

5.0.0

Node.js version

22.10.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

CachyOS 2024.10.03

Description

When using RouteShorthandOptions to declare the variable for the options of a route handler, it breaks its type safety, this doesn't happen if the variables isn't explicit typed.

import Fastify from 'fastify';
import { fastifyAutoload } from '@fastify/autoload';
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox';

const app = Fastify()
  .withTypeProvider<TypeBoxTypeProvider>()
  .register(fastifyAutoload, {
    dir: `${import.meta.dirname}/routes`,
    routeParams: true,
  });

app.listen({ port: 8080 });
import {
  FastifyPluginAsyncTypebox,
  Type,
} from '@fastify/type-provider-typebox';
import { RouteShorthandOptions } from 'fastify';

const options: RouteShorthandOptions = {
  schema: {
    querystring: Type.Object({ name: Type.String() }),
    response: {
      200: Type.Object({ greeting: Type.String() }),
    },
  },
};

const route: FastifyPluginAsyncTypebox = async (fastify) => {
  fastify.get('/hello', options, async (request) => {
    return { greeting: `hello ${request.query.name}` };
                                     // ^? request.query is of type unknown
  });
};

export default route;

Link to code that reproduces the bug

No response

Expected Behavior

I hope to get the same type safety as omitting the explicit type declaration

import {
  FastifyPluginAsyncTypebox,
  Type,
} from '@fastify/type-provider-typebox';

const options = {
  schema: {
    querystring: Type.Object({ name: Type.String() }),
    response: {
      200: Type.Object({ greeting: Type.String() }),
    },
  },
};

const route: FastifyPluginAsyncTypebox = async (fastify) => {
  fastify.get('/hello', options, async (request) => {
    return { greeting: `hello ${request.query.name}` };
                                     // ^? request.query is of { name: string }
  });
};

export default route;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions