In my application I have an object of routes like so:
const routes = {
home: () => '/',
user: ({ userId }: { userId: string }) => `/user/${userId}`,
} as const;
type Routes = typeof routes;
type RoutesKey = keyof Routes;
type GetParams<Key extends RoutesKey> = Parameters<
Routes[Key]
>[0] extends undefined
? [undefined?]
: [Parameters<Routes[Key]>[0]];
function get<Path extends RoutesKey>(route: Path, ...params: GetParams<Path>) {
// ...params must be a tuple or passed as a rest parameter --- ERROR
return fetch(routes[route](...params));
}
// This part actually works
get('home');
get('user', { userId: '1' });
The problem I have is when I make a get function, I get type errors. I'm not exactly sure how to deal with passing the parameters, and it like whenever I attempt to twist it in one way or another I get either another error or no type help. I could ofc. assert the ...params [any], and it would work, but would like to find a solution without any. Tho my GetParams helper does return a tuple?
Thanks in advance! :)