Describe the problem
I want to have a number in my route param. So, I created a matcher
Filename: src/params/number.ts
export function match(value): boolean {
return Number.isFinite(Number(value));
}
and a page
Filename: src/[a=number]/+page.ts
export function load({ params }) {
return {
a: params.a, // type: string
};
}
params.a is still inferred as a string but not a number. So, I have to convert it to a number once more, which is repetitive and error-prone(e.g., if I forget to add =number during a refactoring)
return {
a: Number(params.a),
};
Describe the proposed solution
I propose to change match(value): boolean to match<T>(value): T, so it is possible to return any type from match and it will be correctly inferred in load functions.
Filename: src/params/number.ts
export function match(value): number {
const parsed = Number(value);
if (!Number.isFinite(parsed)) {
// throw an error to indicate that value is invalid
throw new Error("not a number");
}
return parsed; // type: number
}
Filename: src/[a=number]/+page.ts
export function load({ params }) {
return {
a: params.a, // type: number
};
}
This would also make it possible to integrate with zod:
Filename: src/params/number.ts
export const match = z.number().parse
Since, this is a non-backwards compatible change, it can be a proposal for sveltekit 2 or the name of the matcher may be changed to something like parse or matchParse etc.
Alternatives considered
-
Importance
would make my life easier
Additional Information
keywords: match, parse, route param, zod
Describe the problem
I want to have a number in my route param. So, I created a matcher
Filename:
src/params/number.tsand a page
Filename:
src/[a=number]/+page.tsparams.ais still inferred as astringbut not anumber. So, I have to convert it to a number once more, which is repetitive and error-prone(e.g., if I forget to add=numberduring a refactoring)Describe the proposed solution
I propose to change
match(value): booleantomatch<T>(value): T, so it is possible to return any type frommatchand it will be correctly inferred inloadfunctions.Filename:
src/params/number.tsFilename:
src/[a=number]/+page.tsThis would also make it possible to integrate with
zod:Filename:
src/params/number.tsSince, this is a non-backwards compatible change, it can be a proposal for sveltekit 2 or the name of the matcher may be changed to something like
parseormatchParseetc.Alternatives considered
-
Importance
would make my life easier
Additional Information
keywords: match, parse, route param, zod