Determine the associated value for a given key within a TypeScript object

I have a structure like this:

type newsItem = {
  img: string;
  slug: newsSlug;
  text: newsText;
};

derived from an enum like this:

export const newsEnum = {
  interesting: "Interesting",
  regions: "Regions",
  contradictory: "Controversial",
  important: "Important",
  actual: "Current",
};

where

type newsSlug = keyof typeof newsEnum;
type newsText = typeof newsEnum[keyof typeof newsEnum];

I am curious, can I define the type of 'slug' as a specific key and then specify 'text' as its corresponding value in the newsEnum enum using TypeScript?

I attempted it but ran into issues:

type newsItem<T extends NewsSlug> = {
  img: string;
  slug: T;
  text: typeof newsEnum[T];
};

This is because I plan to dynamically create an array of these items later on.

Answer №1

Uncertain about the issue at hand? I incorporated the const assertion and kept everything else similar to your code.

export const news = {
  interesting: "Интересно",
  regions: "Регионы",
  contradictory: "Спорно",
  important: "Важно",
  actual: "Актуально",
} as const;

type News = typeof news;
type NewsKeys = keyof News;
type NewsValues = News[NewsKeys];

type NewsLink<T extends NewsKeys> = {
  img: string;
  slug: T;
  text: News[T]
};

I plan to create an array dynamically later on, but I'm not entirely clear on how to proceed with this part. Any insights?

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

Instructions for correctly integrating the ng2-datepicker module into an Angular 2 application

Ng2-datepicker (1.0.6) Angular2 (2.0.0-rc.5) As I attempted to implement it in my HTML following the documentation, I encountered the following error: zone.js:484 Unhandled Promise rejection: Template parse errors: Can't bind to 'ngMode ...

Update the data-value parameter dynamically after a successful Ajax request without utilizing the element's

I have a bunch of different buttons to switch the status of various projects: <div class="btn-group btn-toggle project_status" data-project-id="1" data-form="project_status" data-value="1"> <button class="btn btn-default active">ACTIVE</ ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Eliminating certain buttons within Ember-leaflet-draw

Is there a way to remove specific buttons from the UI in my Ember application that are used for drawing lines, circles, and polygons? I am currently using Leaflet Draw in my project. Here is a snippet of my template.hbs: {{#leaflet-map onLoad=(action &apo ...

Guide on resolving a "res is not defined" issue in Node.js

I've been struggling to test the controller logic for a user validation module, but I keep encountering an error that says "res is not defined" even after trying to define it. How can I properly define it so that it runs through the condition statemen ...

Launching event handlers and applying CSS classes within a single scenario

How can I toggle the visibility of a button based on form field validation in JavaScript? I want to show or hide the button when the .confirm button is clicked, and if the form is valid, add a checkmark to the body element through event listener. The issu ...

Encountering issues with React Apollo hooks after integrating React Native into the monorepo system

I am in the process of setting up a React web app and a React-native app within a monorepo using yarn workspaces. The web and controllers are functioning properly, allowing me to successfully execute graphql queries to my apollo-express server. However, up ...

Avoiding GulpJs freezing with effective error handling techniques

I am currently in the process of converting my sass files to css and encountering some issues. Specifically, I am struggling with handling errors during the sass conversion process. Whenever there is an error, it causes gulp to hang, requiring me to rest ...

Is it possible to trigger a JavaScript function and an AJAX command with just one button click?

I'm looking to achieve a specific functionality using one button within a form. The requirements are as follows: 1) When the button is clicked, it should trigger a JavaScript function that performs animations such as fadeout and fadein. 2) Following ...

Tips for integrating Typescript into a pre-existing Vue 3 project

The contents of my package.json file are as follows: { "name": "view", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve" ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

AngularJS - UI Bootstrap: Easily expand or collapse all items in the Accordion widget

I have created a code to open and close all tabs of an accordion individually using separate 'open' and 'close' buttons. However, it requires me to dynamically add a key value pair (a Boolean value) to my JSON data. What is the best ap ...

Ways to prevent negative values from appearing in the text field

Check out this code snippet on Fiddle. I need help with a text field that should only display positive values. If the input is negative, I want it to be stored in ng-model but not shown in the textbox. function LoginController($scope) { $scope.number = ...

Creating an interactive bootstrap modal: a step-by-step guide

For instance, I have 3 different tags with unique target-data for each one. <a class="btn btn-outline-primary btn-sm" href="#" data-toggle="modal" data-target="#firstdata"> DATA 1 </a> <a class=&q ...

Troubleshooting jQuery masonry problem related to initial display and height settings

Within a div, there is a masonry container with the inline style property display:none. With several divs on the page, clicking their respective buttons during load causes them to switch like a slideshow. This disrupts masonry's ability to calculate t ...

Searching for the perfect jQuery regex to validate date formats

In my application, there is an input box that allows users to enter a string date like "today" or "tomorrow". However, I am facing a new challenge now - dates such as "3 march" or "8 january." The input box includes a dropdown menu feature where users can ...

An issue occurred while using AJAX in jQuery: there was an error converting a circular structure

After consoling JSON.stringify(stateArr), my JSON appears to be correct: { "shipping_options": [{ "id": "1", "name": "Kuala Lumpur", "rate": "222" }, { "id": "2", "name": "Labuan", "rate": "1" }] ...

Transfering information to handlebars in node.js

Being a beginner in node.js, I am currently working on making a get request in my router (index.js). After successfully obtaining the desired result (verified by logging it in console.log), I proceed to parse it into a JSON object and pass it to a render f ...

Remove an item from a complex JSON structure based on the specified name. The function will then return the

Hey there, I'm just starting out with react native and I have an array of objects. My goal is to remove an inner object from this JSON data. [ { Key: 1, exchnageArr: [ { name: ”FX” }, { name: ”MK” ...