typescript code: transforming object values into keys in typescript

Here is a scenario:

const obj1 = {
  a: 'x',
  b: 'y',
  c: 'z',
}

I am looking to automatically create a type like this:

type Type = {
  x: number,
  y: number,
  z: number,
}

I initially considered the following approach:

type Type = {[key in Object.values(obj1)]: number}

However, it did not work as expected.

SOLUTION

Thanks to @jcalz's assistance, I was able to come up with a generic solution:

type ObjectKeysFromValues<
  O extends { [key: string | number]: string | number},
  V = string,
> = Record<O[keyof O], V>

This can be implemented as shown below:

const obj2: ObjectKeysFromValues<typeof obj1> = {
  x: '1',
  y: '1',
  z: '1',
}

or

const obj2: ObjectKeysFromValues<typeof obj1, number> = {
  x: 1,
  y: 1,
  z: 1,
}

Perhaps I should rethink my naming strategy 😂

Answer â„–1

To start, make sure to include "as const" after defining obj1.

const obj1 = {
  a: "x",
  b: "y",
  c: "z",
} as const;

Next, there are two ways to define your type.

Option 1 is using index signatures:

type Type = {
    [P in typeof obj1[keyof typeof obj1]]: number
}

Option 2 involves using the built-in utility type "Record" like this:

type Type = Record<typeof obj1[keyof typeof obj1], number>

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

Exploring TypeAhead functionality in Reactjs 18

I have encountered an issue while using react-bootstrap-typeahead version 5.1.8. The problem arises when I try to utilize the typeahead feature, as it displays an error related to 'name'. Below is my code snippet: import { Typeahead } from " ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

Angular5 - Modify a public variable using an intercept in a static service

Take into account the following Angular service: @Injectable() export class AuthService { public userConnected: UserManageInfo; getManageInfo(): Observable<UserManageInfo> { return this.httpClient .get('api/Account/Man ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

Can a type be established that references a type parameter from a different line?

Exploring the Promise type with an illustration: interface Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

In the process of using SWRInfinite for React Infinite Scrolling, the initial call may be made

Can someone help me understand why my useGetItems hook, which imports the usePagination hook, keeps repeating the first call history every time I scroll? /items?_page=1&_limit=40 /items?_page=1&_limit=40 /items?_page=2&_limit=40 /items?_page=1 ...

I'm curious as to why I am receiving an empty array as a response when I send a post request to the API

I am experiencing an issue while sending data to an API using a post method. I have structured the data in an object as per the server's requirements, but upon posting the object to the API, I receive a response with a status of 200 and an empty array ...

What exactly does "context" refer to in the context of TypeScript and React when using getServerSideProps?

As a beginner in coding, I have a question regarding a specific syntax I recently encountered. I am confused about this particular line of code and couldn't find any helpful explanations online: export async function getServerSideProps(context: GetSer ...

There are no properties shared between type 'dateStyle: string' and type 'DateTimeFormatOptions'

"typescript": "^4.0.3" Can anyone help me resolve the TypeScript error I am encountering in the code below?: components/OrderListItem.tsx const newedate = (_date) => { const options = {dateStyle: 'medium'}; //{ weekday: ...

Mastering Typescript Inversify: The Ultimate Guide to Binding Interfaces with Type Parameters

I am trying to figure out how to bind an interface with a type parameter, but I am unsure of the correct way to do it. Here is the Interface: ... export interface ITestHelper<Entity extends ObjectLiteral> { doSomething(builder: SelectQueryBuilder& ...

Fulfill the promise to retrieve the value contained within

Is there a way to use TypeScript to call the Wikipedia API for retrieving a random page title and save it in a variable for later use? I am struggling with resolving promises as I keep getting ZoneAwarePromise returned. I'm new to both promises and Ty ...

Tips for expanding the functionality of the d3-selection module using TypeScript

I am currently working on a project that involves TypeScript and d3. I have already installed 'd3' and '@types/d3', and my use of d3 looks like this: import * as d3 from 'd3'; const x = d3.scaleLinear ... Everything was goin ...

What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code? Here's what I have ...

Simple method for wrestling with objects in TypeScript HTTP POST responses

Can anyone help me understand how to extract information from an object received through an HTTP POST request? Below is the code I am using: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); The issue aris ...

unable to call a function within Angular

To create a dynamic menu, I am utilizing primeng's menu panel. Firstly, I declare my item variable: items: MenuItem[]=[]; I have two JavaScript objects to incorporate into the menu, namely groupsItem and ejsItem. Here is their structure: groupsI ...

What materials are required in order to receive messages and information through my Contact page?

Currently, I am pondering the optimal method for gathering information from my Contact page. I have already created a form; however, I'm unsure how to send the gathered data to myself since I am relatively new to Web development. Angular is the framew ...

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...