Is it possible to dynamically synchronize object types in TypeScript based on each other?

In my quest to sync my Russian and English language dictionaries dynamically, I encounter a challenge.

Imagine having two objects:

const ru = {
'page.main.hello': 'Привет!'
}
const en = {
'page.main.hello': 'Hi!'
}

If I add a key to the "ru" object, I want TypeScript to automatically update the "en" object by adding the same key.

const ru = {
'page.main.hello': 'Привет!'
}

const en = {
'page.main.hello': 'Hi!',
'page.main.bye': 'Bye!'
}

The problem arises when typing errors occur as the key 'page.main.bye' does not exist in the "ru" dictionary.

I attempted using ru: keyof typeof en and en: keyof typeof ru, but due to self-reference, it proved ineffective.

Selecting a base object between the two is not a viable solution to the synced objects dilemma.

Answer №1

Here is the coding solution that I have implemented:

const translations: Record<keyof typeof english, string> = {
  'page.main.hello': 'Bonjour!'
}

const english = {
  'page.main.hello': 'Hello!',
  'page.main.bye': 'Goodbye!'
}

This approach offers a good level of flexibility, contrary to my initial assumptions. Additionally, it simplifies the process of defining dictionary keys as they only need to be specified in the "english" object.

Answer №2

To achieve this, a simple method would be to create a new interface that defines the specific keys required. By using this interface, you can establish the definitive set of keys for the objects involved.

interface LanguageKeys {
  'page.main.hello': string;
  'page.main.bye': string;
}

const russian: LanguageKeys = {
  // This will result in a type error as the key 'page.main.bye' is missing
  'page.main.hello': 'Привет!'
}

const english: LanguageKeys = {
  'page.main.hello': 'Hi!',
  'page.main.bye': 'Bye!'
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges encountered while deploying a NextJS project with TypeScript on Vercel

Encountering an error on Vercel during the build deploy process. The error message says: https://i.stack.imgur.com/Wk0Rw.png Oddly, the command pnpm run build works smoothly on my PC. Both it and the linting work fine. Upon inspecting the code, I noticed ...

Component that can be used multiple times to load data

I am currently working on a react/nextjs/redux application where each component needs to call a different backend API. The main challenge I am facing is the lack of reusability in loading data components due to some repetitive code that I would like to el ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

When attempting to utilize yarn link, I receive an error message indicating that the other folder is not recognized as a module

After successfully running "yarn link," I encountered an issue when attempting to use it in a different project. The error message displayed was ../../.tsx is not a module. What could be causing this problem? const App: React.FC = () => { const [op ...

Merging sort and uniq functionalities to create a single function in JavaScript

I've been working with the sortBy and uniqBy functions, but I find myself iterating over the array twice when using the combined sortUniqBy. If you want to check out the code, feel free to click on this link to the codesandbox. Here's a snippet o ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

The MUI theme seems to be missing its application

As a newcomer to MUI, I'm facing challenges when trying to apply a custom theme. My goal was to create a new variant for the button using the code snippet below: // @ts-nocheck import React, {FC} from 'react'; import { createTheme, ThemeProv ...

Tips for creating a Sequelize table with TypeScript the right way

My current challenge involves: interface PersonI { id?: number | null, firstName: string, lastName: string } @Table( { tableName: 'person', timestamps: true } ) class Person extends Model implements PersonI ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Filter array to only include the most recent items with unique names (javascript)

I'm trying to retrieve the most recent result for each unique name using javascript. Is there a straightforward way to accomplish this in javascript? This question was inspired by a similar SQL post found here: Get Latest Rates For Each Distinct Rate ...

Dealing with errors in Next.js 13 with middleware: a comprehensive guide

My attempt to manage exceptions in Next.js 13 using middleware is not producing the desired results. Below is my current code: import { NextRequest, NextFetchEvent, NextResponse } from "next/server" export function middleware(req: NextRequest, e ...

Issue encountered while initializing a fresh project with Angular CLI version 13.1.0

I encountered an issue while trying to create a new project with Angular CLI v13.1.0 \ Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

Handle and manage errors within the controller in Express.js to prevent the further execution of asynchronous functions

Consider a scenario where there is an API endpoint /register, designed to register new users in an application. The function utilized is asynchronous, as an attempt is made to incorporate an asynchronous process within an AuthController when performing pas ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

Depend on a mapping function to assign a value to every option within a discriminated union

While utilizing all variations of a discriminated union with conditional if statements in TypeScript, the type is narrowed down to the specific variant. To achieve the same effect by expressing the logic through a mapping from the discriminant to a funct ...

Issues with updating values in Angular form controls are not being resolved even with the use of [formControl].valueChanges

[formControl].valueChanges is not triggering .html <span>Test</span> <input type="number" [formControl]="testForm"> .ts testData: EventEmitter<any> = new EventEmitter<any>(); testForm: FromCo ...

Pass the variant value from Shopify/Restyle to the child component in a seamless way

Forgive me if this question has already been addressed elsewhere. Is there a secure method to transmit variant information to child components? I'm attempting to craft a personalized Button component using the useRestyle hook as outlined in the follo ...

Defining a JSON file interface in Angular to populate a dropdown box with dependencies

I've embarked on an exciting project to develop a cascading dropdown box filter, and it's proving to be quite challenging. I'm taking it step by step to ensure clarity. I have obtained a JSON file containing the data required to populate de ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Is there a way to extract various pieces of data from a single object and implement them in a NextJs 13 application directory?

My Django RESTapi is providing output data in the following format: { "count": 1000, "next": "http://127.0.0.1:8000/store/products/?page=2", "previous": null, "results": [ { "id": 648, ...