We use https://react.i18next.com/ to handle multi-language translations in our app.
This article assumes you already have react-i18next set up for your project. If you're new to this library, follow the Getting Started Guide
Up until now finding incorrect translation keys, or missing translations was a dread. We had to catch any issues ourselves without any IDE support and this sucked. After adding typesafety to our translations I found plenty of previously hidden issues in our codebase, and could fix them in one go. Isn't typescript just the best? 😉
Adding typesafety for react-i18next
Here's a simplified example of how you can add typesafety for your react-i18next project:
Create a type definitions file for your translations module.
In vite and cra you can put a new file in the @types
folder: src/@types/react-i18next.d.ts
Thats it. Now you should have fully typesafe translations and autocomplete.
How to correctly use the useTranslation
hook
Typescript is now very strict about how and which translations you can use, depending on your usage of the useTranslation
hook.
using a single namespace
if using useTranslate('singleNS')
dont use NS prefix in trans keys
using multiple namespaces
if using useTranslate(['nsA', 'nsB'])
this will force you to use NS prefixes for everything
using multiple namespaces with the first as default
if using useTranslate(['nsA', 'nsB'] as const)
-> this will allow you to skip the namespace prefix for nsA
, namespaces are required for nsB
and further.
using computed translation key names
if you construct translation keys via functions or lookups make sure you return the strings as const
so the type checker evaluates them as their value, and not as string
The same principal applies when using functions to generate the translation keys. Make sure they dont return the key with the return type string, but the full string as const / union.