I'm in a codebase that uses typescript to share API interface contracts between server (express) and react). These shared types are organized into namespaces, and work well but can be a bit verbose in express.
For example:
// Shared API type in global file
export namespace GetRecordAPI {
export type PathParams = {
recordId: string;
};
export type RequestBody = {};
export type QueryParams = {
date: string;
};
export type Response = APIResponseValidation & {
record: RecordData;
};
}
// Express route controller
type GetRecordHandler = RequestHandler<
GetRecordAPI.PathParams,
GetRecordAPI.Response,
GetRecordAPI.RequestBody,
GetRecordAPI.QueryParams
>;
export const getRecord: GetRecordHandler = async (req, res, next) => {
// ...
};
The problem is that it becomes pretty verbose to construct the RequestHandler for each express route controller. Since everything is organized consistently in namespaces, I'd really like to have a global typescript wrapper that stitches it all together by passing the namespace.
// Global helper
type ExpressHandler<T> = RequestHandler<T.PathParams, T.Response, T.RequestBody, T.QueryParams>;
// Express route controller
export const getRecord: ExpressHandler<GetRecordAPI> = async (req, res, next) => {
// ...
};
Is something like this even remotely possible? The react app uses each exported type within the namespace independently, so it would be ideal to keep this structure, for now.