Prerequisites
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.
Prerequisites
Issue
Premise
Not really sure if this is a feature or a bug since methods on
Replythat modify what the response schema should be, don't actually narrow at the type level when there is a broader type available.For example:
The reason it does not show a type error is because the type applied on the payload is
string | 'Success!and sincestringis broader than'Success!', it only appliesstring.Proposed Solution
The type can be narrowed by modifying generics in:
fastify/types/reply.d.ts
Line 34 in d0d3696
to something like this:
For consistency, this would need to be applied to the
statusmethod as well.Furthermore, some extra Typescript-ing would be needed to account for response schemas with keys like
2xxbut 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.