Update: thanks to https://stackoverflow.com/users/5575595/drag13 completed version can be found here: https://github.com/web-ridge/react-ridge-translations/blob/main/src/index.ts
I'm working on a translation library for React / React Native but I can't get the types to work.
https://github.com/web-ridge/react-ridge-translations
You can create a translation in the following way
// first describe which languages are allowed/required (Typescript)
type TranslationLanguages = {
nl: string
fr: string
en: string
}
// create a translation object with your translations
export default const translate = createTranslations<TranslationLanguages>({
homeScreen:{
yesText: {
nl: 'Ja',
fr: 'Oui',
be: 'Yes',
},
welcomeText: ({ firstName }: { firstName: string }) => ({
nl: `Hoi ${firstName}`,
fr: `Hello ${firstName}`,
be: `Hello ${firstName}`,
}),
}
}, {
language: 'nl',
fallback: 'en',
})
The library changes the object to the following
{
homeScreen:{
yesText: 'Ja',
welcomeText: ({ firstName }: { firstName: string }) => `Hoi ${firstName}`,
}
}
In your component you will use the types in this way
const {yesText,welcomeText} = translate.use().appScreen
It won't autocomplete the types.
Library code (simplified)
type val<T> = (...params: any[]) => T
type val1<T> = T
type Translations<T> = {
[group: string]: {
[key: string]: val<T> | val1<T>
},
}
type TranslationsObject<T> = {
translations: Translations<string>,
use: () => Translations<string>;
}
export function createTranslations<T>(t: Translations<T>): TranslationsObject<T>
How can I let Typescript understand that it needs to autocomplete?