在我的应用程序中,我有这样一个路由对象:
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' });
我的问题是,当我生成get函数时,会出现类型错误.我不太确定如何处理传递参数的问题,就像每当我试图以这样或那样的方式扭曲它时,我要么得到另一个错误,要么没有类型帮助.我可以用ofc.断言...params[any],它可以工作,但希望找到一个没有任何参数的解决方案.我的GetParams助手是否返回元组?
提前感谢!:)