amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

Match types of #1392

Closed shadoath closed 1 month ago

shadoath commented 1 month ago

Is your feature request related to a problem? Please describe.

I'm working to make both useTranslations and createTranslator have a matching type

I'm going outside the norm to use createTranslator server side via a global.

Here is a smushed-together version of my code.

import { createTranslator, useTranslations } from "next-intl"

export const LOCALE_EN = "en" as const
export const LOCALE_PT = "pt" as const
export const LOCALES = [LOCALE_EN, LOCALE_PT] as const
export type LocaleVT = (typeof LOCALES)[number]

export type Translation1 = ReturnType<typeof useTranslations>
export type Translation2 = ReturnType<typeof createTranslator>

export type Translation = Translation2

import en from "messages/en"
import pt from "messages/pt"

declare global {
  var enMessages: Translation
  var ptMessages: Translation
}

const enMessages = global.enMessages || createTranslator({ locale: LOCALE_EN, messages: en })
const ptMessages = global.ptMessages || createTranslator({ locale: LOCALE_PT, messages: pt })

if (!global.enMessages) global.enMessages = enMessages
if (!global.ptMessages) global.ptMessages = ptMessages

export const getServerTranslations = (locale: string) => {
  switch (locale) {
    case LOCALE_EN:
      return enMessages
    case LOCALE_PT:
      return ptMessages
    default:
      return enMessages
  }
}

Describe the solution you'd like

I tried something like:

// Not valid 
const t = enMessages("basic.Back")
// Valid
const t2 = enMessages("Back")

Which is the opposite of what I would expect as I provided no namespace.

Describe alternatives you've considered

I want to keep the type safety and not need to use an any type for the work.

My current thought is to stop using useTranslations

amannn commented 1 month ago

I'll move this to a discussion since it seems to be a rather special usage question.

As a side note, you can pass a locale to getTranslations({locale, namespace: 'basic'}) if you need to use multiple locales in server-only code.