Skip to content

Infer routes without using as const #1444

Closed
@hunyan-io

Description

@hunyan-io

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.

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