Scaling Localization with TypeScript Translation Objects
Translating Experiences
Maintaining a multilingual portfolio often leads to messy string management. As your project grows, hardcoding text inside components becomes a maintenance nightmare, making it nearly impossible to keep UI copy consistent and up-to-date across different regions.
The Strategy: Centralized Translation Objects
In the my-portfolio project, I recently moved away from scattered string literals in favor of a centralized translation object. This approach separates content from structure, allowing for easier scaling and cleaner component logic.
By defining a typed dictionary for your site copy, you can ensure that every string is accounted for and easily accessible throughout your TypeScript application.
Implementation
Instead of inline text, define a translation manifest that maps keys to localized values. Here is how you can structure this in TypeScript:
interface Translation {
hello: string;
projectsTitle: string;
}
const en: Translation = {
hello: 'Hello, I am a developer',
projectsTitle: 'My Recent Work'
};
export const getTranslation = (lang: 'en'): Translation => {
const dictionary = { en };
return dictionary[lang];
};
This pattern provides several benefits:
- Type Safety: TypeScript ensures you never reference a non-existent translation key.
- Maintainability: Changing a heading or a greeting requires updating only one source file.
- Scalability: Adding a new language is as simple as creating a new object that satisfies the
Translationinterface.
Benefits of Decoupling
Moving to an object-based translation system shifts the focus from "where is this string used" to "what is this piece of content." It simplifies testing, as you can easily swap out the entire dictionary object to verify layout adjustments without needing to manually modify JSX/TSX files.
Key Takeaway
Stop hardcoding strings directly in your components. Define a central translation interface today to ensure your content remains consistent and your codebase stays modular as your portfolio grows. Start by pulling out just your top-level headings into a shared configuration file.
Generated with Gitvlg.com