Skip to content
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

Strictly typed useLocale #1377

Open
amannn opened this issue Sep 27, 2024 · 1 comment
Open

Strictly typed useLocale #1377

amannn opened this issue Sep 27, 2024 · 1 comment
Labels
area: ergonomics enhancement New feature or request

Comments

@amannn
Copy link
Owner

amannn commented Sep 27, 2024

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

Currently, useLocale returns a string. This is mostly fine, but APIs that ask for strictly typed locales (e.g. locale of getPathname currently) make this not easy to assign.

The reason for this is that the locales are passed to a navigation factory function, but not useLocale (which is imported from next-intl).

Describe the solution you'd like

Either all APIs should use a strictly typed locale or none—a mixture requires workarounds.

Similar to strictly typed messages and formats, we could allow the user to provide the list of locales globally. This would work for both global APIs like useLocale as well as the navigation APIs. At this point we could consider registering all global shapes under a single type namespace.

@amannn
Copy link
Owner Author

amannn commented Nov 1, 2024

This (and a bit more) is coming in v4: #1495

amannn added a commit that referenced this issue Nov 1, 2024
**Changes**
- Revamps the API to augment types by getting rid of the global
`IntlMessages` and `IntlFormats` in favor of a more general `AppConfig`
that is scoped to `next-intl`.
- Adds support for strictly-typing the locale across `useLocale` as well
as the navigation APIs.
- Adds `import {Locale} from 'next-intl';` as a convenience API to be
reused wherever a `locale` is passed around.
- Add `hasLocale(locales, candidate)` API for simplified checking of
whether a locale is available with TypeScript.
- Adds a new `import {Messages} from 'next-intl;` type that corresponds
to the `Messages` you've provided in `AppConfig` (probably rarely
needed).


**Example:**

```tsx
// global.d.ts

import {routing} from '@/i18n/routing';
import {formats} from '@/i18n/request';
import en from './messages/en.json';

declare module 'next-intl' {
  interface AppConfig {
    Locale: (typeof routing.locales)[number];
    Formats: typeof formats;
    Messages: typeof en;
  }
}
```

**→ [Proposed
docs](https://next-intl-docs-git-feat-augmented-config-next-intl.vercel.app/docs/workflows/typescript)**

Fixes #1377
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: ergonomics enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant