Skip to content

Parse param in matcher #10407

Description

@olehmisar

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

Metadata

Metadata

Assignees

No one assigned

    Fields

    No fields configured for Feature.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions