Strong-typed I18N in React
Adding i18n support to your app can be painful. Extracting all text strings from JSX to translation files and replacing them with keys is meticulous monotonous work. One small misspelling and oops you got a bug. But what if I tell you, that you can use TypeScript to validate translations?
The idea is pretty simple: translations are stored in JSON files as a key-value dictionary, TypeScript is able to parse them and determine the type of translation dictionary, let’s call this type Translation
. Any popular i18n solution provides a function for getting a translated string by key, let’s call it t
. So, the only thing you need is to ensure that the key passed to t
function has keyof Translation
type. As a result, TypeScript will validate all translation keys and autocomplete them in your IDE.
Let me show an example of how to use this technique withreact-i18next
library.
React-i18next
React-i18next is a React wrapper for i18next framework. It supports all required features for internationalization like translations templating, namespaces, dynamic translations loading, and many others. Also i18next
has adapters for other frontend frameworks like VueJS…