Skip to content

ts-pattern and type-route #136

Description

@mikecann

Hey I really like the look of this library and am coming from chicane router (https://swan-io.github.io/chicane/route-pattern-syntax) I was wondering if there was a way to get the lib to work with ts-pattern.

Specifically I am trying to get the Nested Routes feature to work.

For example, this is my basic set of routes:

import { createRouter, defineRoute, param, createGroup } from "type-route";
import { match } from "ts-pattern";

const newUser = defineRoute({}, (p) => `/new-user`);

export const { RouteProvider, useRoute, routes } = createRouter({
  root: defineRoute("/"),
  home: defineRoute("/home"),
  newUser,
  newUserTerms: newUser.extend(`/terms`),
  newUserWelcome: newUser.extend(`/terms`),
});

export const groups = {
  newUser: createGroup([routes.newUser, routes.newUserTerms, routes.newUserWelcome]),
};

export const matchPattern = match;

I am then attempting to use it like so:

export const TypeRouterRoutes: React.FC<Props> = React.memo(({}) => {
  const route = useRoute();
  const logger = useLogger(`TypeRouterRoutes`);

  logger.log(`RENDER`, route);

  return (
    <>
      {matchRoute(route)
        .with({ name: false }, () => <Box>404</Box>)
        .with({ name: "root" }, () => <Box>ROOT</Box>)
        .with({ name: "home" }, () => <Box>HOME</Box>)
        .with(
          Pattern.when((r) => groups.newUser.has(r)),
          () => <Box>NEW USER</Box>,
        )
        .exhaustive()}
    </>
  );
  });

I am however unfortunately getting an error at the "exhaustive" part:

image

I believe this is because for some reason the type-narrowing in the type-guard of this part isnt working as expected:

.with(
          Pattern.when((r) => groups.newUser.has(r)),
          () => <Box>NEW USER</Box>,
        )

Do you have any experience with this or any suggestions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions