Is there a way for the autocomplete feature to suggest the keys that are returned by the hook?

I have created a custom hook that should return the appropriate text options based on the specified region. However, I am unsure about the specific generic type required to access the available object keys in the output. Currently, the keys are not being recognized.

Here is the code for the hook with an incomplete generic:

interface Translate {
    [keys: string]: {
        ru: string
        en: string
    }
}

export function useTranslate<T extends Translate, R extends keyof T>(translate: T) {
    const lang = Location.language
    const response: { [keys: R]: string } = {}

    Object.keys(translate).forEach(name => {
        if (lang === 'ru-RU') {
            response[name] = translate[name].ru
        } else {
            response[name] = translate[name].en
        }
    })

    return response
}

Example usage of the hook:

    const translate = useTranslate({
        home: {
            en: 'Home',
            ru: 'Главная',
        },
        shop: {
            en: 'Shop',
            ru: 'Магазин',
        },
        suppliers: {
            en: 'Suppliers',
            ru: 'Поставщикам',
        },
        faq: {
            en: 'FAQ',
            ru: 'FAQ',
        },
        reviews: {
            en: 'Reviews',
            ru: 'Отзывы',
        },
    })

//return if EN region {
home: 'Home',
shop: 'Shop',
...
}
//return if RU region {
home: 'Главная',
shop: 'Магазин',
...
}

The hook will return either the English or Russian version, but not both.

TODO: Enable autocomplete to suggest which keys can be referenced.

Thank you in advance for your help!

Answer №1

Below is my proposed solution. The method incorporates type-safe parameters and return values, though it internally utilizes any. I trust this approach aligns with your requirements.

export function utilizeTranslate<T extends Translation>(translation: T): Record<keyof T, string> {
    const language = Location.language;
    const result: any = {};

    Object.keys(translation).forEach(key => {
        if (language === 'ru-RU') {
            result[key] = translation[key].ru
        } else {
            result[key] = translation[key].en
        }
    })

    return result
}

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

How to exchange variables and trigger events between jQuery and C# using AJAX

Hey there! So I've got this jQuery snippet that's using jqvmaps to display a world map and interact with it: <script type="text/javascript" lang="js> $(document).ready(function(){ jQuery('#vmap').vectorMap( ...

Utilize express compression in Node.js to compress JSON data from the REST API endpoint

I recently developed a small RESTful application using Node.js. I attempted to compress the JSON data returned by an API request using Express and compression, but unfortunately it did not work as expected. var express = require('express'); var ...

Converting HTML to PDF with Angular 2

I'm looking for a solution to convert an HTML template to PDF and download the file in Angular 2. Specifically, I need TypeScript code that can achieve this. Can anyone provide guidance or share some sample code? ...

Prevent mobile view from activating when zoomed in on the screen

I've built a webpage with a responsive design that adjusts to mobile view on mobile devices or when the screen size is reduced using developer tools. While this functionality works correctly, I have noticed that the design also switches to mobile vie ...

A Vue filtering feature that consistently adds 5 additional elements upon each use

I was wondering, how can I create a computed property filter function that always adds 5 more elements to the current array? Here are more details: Template: <span class="box-content" v-for="item in activeItems" :key="item.id"> <img class=" ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

the document is exhibiting curious behavior

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Title</title> <script language="JavaScript"> <!-- function displayTags() { ...

Blending HTML5, CSS, and JavaScript

I'm currently in the process of customizing an editable CSS table that I found on CodePen, but I'm facing some challenges with getting the HTML5, CSS, JS, and JQuery components to function as desired. Here is the link to the original CodePen snip ...

How do I specify filter selectors for events passed as an object in JQuery's on() method?

I've been pondering about the second syntax of JQuery's on() method where events are passed as an object: services.on({ 'mouseenter': function(e){ console.log('enter', e.target); }, 'mouseleave': function ...

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

Socket.io filters incoming data for xss vulnerabilities

I am currently utilizing socket.io in expressjs 3 and I'm looking to sanitize incoming messages using express-validator. Here's the code snippet I have: var expressValidator = require('express-validator') , sanitize = require('exp ...

What is the purpose of the setDrawRange function in the Three.js library?

I've been diving into a three.js codebase. While studying the code and the documentation, there's one thing that's puzzling me. In this particular code snippet. http://jsfiddle.net/w67tzfhx/ there exists the following piece of code. fun ...

Tips for sending multiple forms and having PHP interpret it as a single form using $.ajax

I am working on an email function using $.ajax with 3 different forms that are loaded through an ajax request. When a user clicks on a button, the current form will disappear and a new form will appear. The challenge I am facing is how to send data from al ...

Tips for sending eventData parameters to .on() by utilizing the .trigger() function from jQuery?

My event handler on the <select> element looks like this: select.on("change", null, { tbody: $("#tbody"), colspan: 5, onLoad: onLoadHandler, }, onSelectChange); Inside the onSelectChange function, I access these parameters via the event ...

Passing intricate data structure from Angular to SignalR

I am encountering an issue when trying to send a complex object to my SignalR hub. The JavaScript object I'm sending matches perfectly with my C# object, so theoretically everything should be functioning correctly. However, for some reason, my UpdateE ...

Should one consider using Eval?

I encountered a scenario where I needed to dynamically retrieve the object value from an array that contained object keys retrieved from an API. I opted for a solution that involved using the eval function. class App extends React.Component { constru ...

Guide to creating a customizable confirmation dialog using Bootstrap modals and jQuery

Is there a way to use a reusable modal dialog for confirmation before executing 2 different functions? I have tried passing the function to be called to confirmDialog(), but it causes the function to 'stack' for subsequent confirmations. I have ...

The Cal.com vanilla javascript integration does not function properly when used with Svelte

I have been trying to integrate cal.com into a SvelteKit website, but I am facing difficulties implementing it using vanilla JavaScript as per the official documentation. While following the instructions provided for vanilla JavaScript, I had success with ...

Can you provide the date time format used in the JSTL fmt tag?

To display date and time in JSTL, the fmt tag can be utilized. Details can be found here In order to format the date for use with front end tools like the datatable, a specific date format needs to be specified. By using parameters such as type or dateSty ...

What is the best way to transfer an array of objects between two components in React?

I've exhausted all the solutions found online, but I'm still facing a persistent issue. Despite my efforts, whenever I try to log information in another component, it keeps showing as undefined. (Just to clarify, the data being dealt with is an ...