Skip to content

Instantly share code, notes, and snippets.

@grizmio
Created October 23, 2022 19:32
Show Gist options
  • Save grizmio/499b551f2773ba97300d67587be809dc to your computer and use it in GitHub Desktop.
Save grizmio/499b551f2773ba97300d67587be809dc to your computer and use it in GitHub Desktop.
Typescript traducciones en un enum, y no más strings weando
Lo uso con expo/reactnative, pero sirve para cualquier proyecto con typescript
Para agregar las traducciones, agregar al:
enum Words {
Después los archivos de traducciones ingles y español llorarán
// I18nService.ts
import * as Localization from 'expo-localization';
import { I18n } from 'i18n-js';
import { ITranslationLanguage } from '../interfaces/ITranslationLanguage';
import EnglishTranslation from '../translations/EnglishTranslation';
import SpanishTranslation from '../translations/SpanishTranslation';
class I18nService extends I18n
{
static #_instance?: I18nService;
constructor() {
const translations: ITranslationLanguage = {
en: EnglishTranslation,
es: SpanishTranslation,
};
super(translations);
this.locale = Localization.locale;
this.enableFallback = true;
this.locale = 'es';
}
public static getInstance(): I18nService {
if (!I18nService.#_instance) {
I18nService.#_instance = new I18nService();
}
return I18nService.#_instance;
}
}
enum Words {
user_name,
user_lastname,
get_actions,
save,
}
const WordsHandler = {
get: function (target: any, prop: string, receiver: any) {
return I18nService.getInstance().t(prop);
},
}
const Tr = new Proxy(Words, WordsHandler);
// gracias https://stackoverflow.com/questions/39701524/does-typescript-allow-an-enum-to-be-assigned-to-an-interfaces-object-key
type EnumKeys = keyof typeof Words;
type EnumKeyFields = {[key in EnumKeys]:string};
interface IWords extends EnumKeyFields{}
export {Tr, Words, IWords};
// archivos de traducciones por ejemplo EnglishTranslation.ts
import { IWords } from "../lib/I18nService";
const EnglishTranslation: IWords = {
user_name: 'name',
user_lastname: 'lastname',
get_actions: 'Get Actions',
save: 'save'
}
export default EnglishTranslation;
// en español SpanishTranslation.ts
import { IWords } from "../lib/I18nService";
const SpanishTranslation: IWords = {
user_name: 'nombre',
user_lastname: 'apellido',
get_actions: 'Obtener acciones',
save: 'guardar',
}
export default SpanishTranslation;
// Se usa:
import { Tr } from '../lib/Tr';
<Button
title={Tr.save}
color="#f194ff"
onPress={saveNewAction}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment