nuxt-modules / i18n

I18n module for Nuxt
https://i18n.nuxtjs.org
MIT License
1.71k stars 478 forks source link

feat: generate `Locale` type based on configuration #3025

Closed BobbieGoede closed 2 months ago

BobbieGoede commented 2 months ago

πŸ”— Linked issue

❓ Type of change

πŸ“š Description

This changes type generation to narrow the Locale type to the configured locales, this way functions that accept a locale parameter (such as our composables) will have proper autocompletion for all configured locales.

@kazupon There's still an issue/quirk with the type, I'm don't know how to narrow the locale property on the Composer type in the same way, so currently the following would cause a type error:

const { locale } = useI18n()
const switchLocalePath = useSwitchLocalePath()

switchLocalePath(locale.value) // Argument of type 'string' is not assignable to parameter of type 'Locale'.

Maybe you know how to resolve this? I don't think this should be merged while this issue is present πŸ˜…

Also working on this https://github.com/BobbieGoede/i18n/pull/49.

πŸ“ Checklist

kazupon commented 2 months ago

@BobbieGoede Hmm, πŸ€” The locale of the current Compose is resolved by the type parameter as locale: WritableComputedRef<Locales>.

https://github.com/intlify/vue-i18n/blob/c03fec09f9c3f9f16f8773295523a8d693e9ce0b/packages/vue-i18n-core/src/composer.ts#L1268-L1296

To support nuxt-i18n use cases, this could be extended more on the Vue I18n side.

e.g. locale: IsNever<CustomLocales> extends true ? WritableComputedRef<Locales> : WritableComputedRef<CustomLocale> .

It may be possible to dynamically extend the locale.

BobbieGoede commented 2 months ago

@kazupon I have a possible solution here https://github.com/intlify/vue-i18n/pull/1890, I have updated this PR to make use of that solution. Let me know if this works for you locally or if a different approach is preferred.