I am using typebox for generating types and schemas for a REST-API. I would like to organize REST-resources like this:
{
querySchema: TSchema;
responseSchema: TSchema;
get: (query : QueryType) => ResponseType;
}
Where QueryType = Static<typeof querySchema>
etc.
Right now, I have a Type that takes typeof querySchema
as template arguments:
type Resource<Q extends TSchema, R extends TSchema> =
{
querySchema: Q;
responseSchema: R;
get: (query: Satic<Q>) => Static<R>
}
Is there a way to avoid having to use template types? I would like to have something like this:
type Resource =
{
querySchema: infer Q; // <-- infer Q from querySchema
responseSchema: infer R;
get: (query: Satic<Q>) => Static<R>
}
I have tried using a function as a "wrapper" around the type with no success:
const resource = <T>(
r : T extends Resource<infer Q, infer R> ?
Resource<Q, R> :
never,
) => r;
resource({ querySchema, responseSchema, ... }) // querySchema is not assignable to type 'never'.
Is there a way to automatically infer the template arguments in Typescript?
Edit:
The behavior I am looking for is to be able to do this:
const users = resource(
{
// querySchema from typebox
querySchema: Type.Object(...),
/* this is where I would like TS to understand that q is of
* type Static<typeof querySchema>
*
*/
get: (q) => { ... }
}
)