nextjs-routes icon indicating copy to clipboard operation
nextjs-routes copied to clipboard

Typed locales if i18n is configured

Open floflock opened this issue 3 years ago • 1 comments

The standard type for locale, for example in const { locale } = useRouter()is always string|undefined.

undefined is only applicable, if i18n is not configured.

What do you mean, is it in the scope of the package that locale and locales are typed properly related to the configuration in the next.config.js?

A config which looks like this...

{
module.exports = {
  i18n: {
    localeDetection: true,
    defaultLocale: 'de-DE',
    locales: ['de-AT', 'de-DE', 'de-CH', 'en-FR', 'en-IT', 'en-GB', 'en-US']
  }
}

... would result into a type override which looks like this:

declare module 'next/router' {
  import type { NextRouter as NextBaseRouter } from 'next/dist/client/router'
  export * from 'next/router'
  export { default } from 'next/router'

  type NextRouter = Omit<NextBaseRouter, 'locale'> & {
    locale: ['de-AT', 'de-DE', 'de-CH', 'en-FR', 'en-IT', 'en-GB', 'en-US']
  }

  export type { NextRouter }

  export function useRouter(): NextRouter
}

This is just a quick draft. We need to dig deeper into the package as, unfortunately, locale is typed on many code pieces in the routing types.

Looking forward for feedback about the idea. Maybe an v1 feature as well...

floflock avatar Aug 21 '22 14:08 floflock

Thanks @floflock, I think this would be a good addition. I would like any solution to consider intl holistically, including #19

tatethurston avatar Aug 22 '22 00:08 tatethurston