Skip to content

Type narrowing on FastifyReply #4755

@aadito123

Description

@aadito123

Prerequisites

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

Issue

Premise

Not really sure if this is a feature or a bug since methods on Reply that modify what the response schema should be, don't actually narrow at the type level when there is a broader type available.

For example:

fastify.post('/',
    {
      schema: {
        response: {
          200: Type.Literal('Success!'), // strict string literal
          500: Type.String(), // broader string
        },
      },
    } as const,
    async (_, reply) => {
        // this should be a type error but it isn't
        reply.code(200).send('Hiya!');
    }
);

The reason it does not show a type error is because the type applied on the payload is string | 'Success! and since string is broader than 'Success!', it only applies string.

Proposed Solution

The type can be narrowed by modifying generics in:

code(statusCode: number): FastifyReply<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider>;

to something like this:

code<T extends keyof SchemaCompiler['response']>(statusCode: T): FastifyReply<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, CallTypeProvider<TypeProvider, SchemaCompiler['response'][T]>>;

For consistency, this would need to be applied to the status method as well.

Furthermore, some extra Typescript-ing would be needed to account for response schemas with keys like 2xx but should be relatively simple to implement with string literals.

I would be willing to make the pull request for this if this is something that seems useful.

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