我对函数 createRouting
有问题,它实际上应该返回与它得到的一样。
但目前它返回它得到的最简单的表示。
这是代码:
type ParamValue = number | string;
type Params<Keys extends string = string> = {
[K in Keys]: (rawParams: Record<string, ParamValue>) => ParamValue;
};
type NoInfer<T> = [T][T extends any ? 0 : never];
class RouteConfig<RouteKey, P extends Params> {
constructor(
public config: {
params?: P;
name?: RouteKey;
validate: (
loc: string,
params: NoInfer<P> extends Params<infer PKeys>
? { [K in PKeys]: ReturnType<P[K]> }
: never,
) => boolean;
path: (
params: NoInfer<P> extends Params<infer PKeys>
? { [K in PKeys]: ReturnType<P[K]> }
: never,
) => string;
},
) {}
}
const enum RouteName {
Main,
}
export const createRouting = <RouteKeys extends string | number, T = any>(
routes: {
[K in RouteKeys]: T;
},
): {
[K in RouteKeys]: T extends RouteConfig<infer RK, infer RP>
? RP extends Params<infer PK>
? RouteConfig<RK, Params<PK>>
: never
: never;
} => {
return routes as any;
};
const routing = createRouting<RouteName>({
[RouteName.Main]: new RouteConfig({
name: RouteName.Main as const,
params: {
foo: (params) => (params.foo && +params.foo) || 0,
bar: () => 66,
} as const,
validate: (location, params) => {
const barExp = params.bar.toExponential(15);
const fooExp = params.foo.toExponential(15);
if (barExp + fooExp) return true;
return true;
},
path: ({ foo }) => `/${foo}`,
}),
});
routing[RouteName.Main].config.params.foo;
在最后一行代码中,params
不应是未定义的,并且有两个键 foo
和 bar