Skip to content

Infer routes without using as const #1444

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
hunyan-io opened this issue Jun 16, 2022 · 1 comment
Closed

Infer routes without using as const #1444

hunyan-io opened this issue Jun 16, 2022 · 1 comment

Comments

@hunyan-io
Copy link

What problem does this feature solve?

This allows users to omit the as const when passing the routes array to createRouter options, which results in better DX imo.

What does the proposed API look like?

This might be possible thanks to this issue comment in typescript
microsoft/TypeScript#30680 (comment)

Here is how I think this could be implemented

type Cast<A, B> = A extends B ? A : B

type Narrowable = string | number | bigint | boolean

type Narrow<A> = Cast<
  A,
  [] | (A extends Narrowable ? A : never) | { [K in keyof A]: Narrow<A[K]> }
>

interface RouteRecordRaw {
  path: string
  name: string
}

interface RouterOptions<Routes extends ReadonlyArray<RouteRecordRaw>> {
  routes: Narrow<Routes>
}

function createRouter<Routes extends ReadonlyArray<RouteRecordRaw>>(
  options: RouterOptions<Routes>
) {
  return options
}

const router = createRouter({
  routes: [
    {
      path: '/',
      name: 'home'
    }
  ]
})

The types are recursive but it's possible to change them in a way that infers only the routes array in case there is a nested array that should not be inferred.

@posva
Copy link
Member

posva commented Jun 17, 2022

Thanks, this is interesting! I think that given the status of that API being experimental and how easy as const makes it to stop or start using it, I rather keep it until it gets out of its experimental state. After all, I don't want to force everybody use this experimental API because it has performance implications with large amounts of routes, due to the nature of the types and it would make the fastest computer lag 😆

I didn't know you could narrow a const type like this, It does work with arrays. It's a good trick to remember.

@posva posva closed this as completed Jun 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants