i18n icon indicating copy to clipboard operation
i18n copied to clipboard

useRoute needs suffix to work

Open Chrissi2812 opened this issue 5 months ago • 2 comments

Environment

Reproduction

https://github.com/Chrissi2812/nuxt_bug_reports/tree/i18n/types-router --- Or --- https://stackblitz.com/edit/github-9m9yc3ub

Image

Describe the bug

With the default settings and experimental.typedPages: true the generated types are not correctly picked up.

If I rename RouteNamedMapI18n to RouteNamedMap the types are available.

Additional context

No response

Logs


Chrissi2812 avatar Aug 05 '25 16:08 Chrissi2812

Due to the way this module generates routes the types for useRoute get a bit complicated, this function will expect route names after localization (e.g. slug___en) since the original names no longer exist.

Unfortunately, I think there isn't much we can do besides adding another composable function:

import { useRoute } from "#imports";
import type { RouteLocationNormalizedLoadedI18n, RouteMapI18n } from "vue-router"

/**
 * Returns the current route location, accepts an unlocalized route name as a parameter.
 *
 * This is a wrapper around `useRoute` to provide type safety while keeping the API consistent.
 */
export function useRouteI18n<Name extends keyof RouteMapI18n>(name: Name) {
  return useRoute() as unknown as RouteLocationNormalizedLoadedI18n<typeof name>
}

And its usage would be:

// No error
const route = useRouteI18n('slug')

I'm still exploring other solutions before adding this in a release, but that should work as a workaround.

BobbieGoede avatar Aug 05 '25 18:08 BobbieGoede

I tried the workaround above. Which seemed to work, but it returned the type as any.

I am not sure if this is a problem for me and my project or if this is a general issue.

Digging into RouteLocationNormalizedLoadedI18n in the .nuxt/types/i18n-plugin.d.ts itseems that there are a bunch of unresolved types. vscode shows the following.

type RouteLocationNormalizedLoadedGeneric = /*unresolved*/ any
type RouteMapGeneric = /*unresolved*/ any

These types might be imported from somewhere else, but i couldnt figure it out.

Adding import type { RouteMapGeneric, RouteLocationNormalizedLoadedGeneric } from 'vue-router' to the template seems to do the trick and the useRouteI18n is finally typed.

So im left with two options.

  1. My vscode and project is more f'ed than i thought. (Already have had trouble with typescript being too deep etc..)
  2. The i18n-plugin.d.ts template is missing the import statements

For now, i will workaround this by adding these two imports to auto imports.

BlueBazze avatar Dec 11 '25 14:12 BlueBazze