Conversion from both keys and values of object

0 votes

I have two sets of string values that I want to map from one to the other as a constant object. I want to generate two types from that map: 

  • Keys and 
  • Values
const KeyToVal = {
    MyKey1: 'myValue1',
    MyKey2: 'myValue2',
};

The keys are working well

type Keys = keyof typeof KeyToVal;

But I am having trouble with the compile-time type for values.

All of these converted my Values to string. I also tried referring How to infer typed mapValues using lookups in typescript?, but I either got my adaptations wrong, or the answers didn't fit my problem. 

May 30, 2022 in TypeSript by Logan
• 2,140 points
505 views

1 answer to this question.

0 votes

You could just change the declaration of KeyToVal like this:

const KeyToVal = {
    MyKey1: 'myValue1',
    MyKey2: 'myValue2',
} as const; // <----- add the <as const> here

Then you can create the key types:

type Keys = keyof typeof KeyToVal;

Now you can create the types of values:

type ValuesTypes = typeof KeyToVal[Keys];
answered May 31, 2022 by Nina
• 3,060 points

Related Questions In TypeSript

0 votes
1 answer

Naming of TypeScript's union and intersection types

The type A | B refers to objects which ...READ MORE

answered Jun 10, 2022 in TypeSript by Nina
• 3,060 points
403 views
0 votes
0 answers

What is TypeScript and why would I use it in place of JavaScript?

Can you please describe what the TypeScript ...READ MORE

Jul 18, 2022 in TypeSript by Logan
• 2,140 points
354 views
0 votes
0 answers

Typescript open-api cilent generation and usage of `fetch`

I am trying to generate a typescript ...READ MORE

Jul 18, 2022 in TypeSript by Logan
• 2,140 points
1,537 views
0 votes
1 answer

Cannot access web3 object with typescript and ethereum

You still need to instantiate it first. ...READ MORE

answered Sep 25, 2018 in Blockchain by slayer
• 29,370 points
2,886 views
0 votes
1 answer

How to apply zoom animation for each element of a list in angular?

Hey @Sid, do check if this link ...READ MORE

answered Jul 30, 2019 in Others by Vardhan
• 13,150 points
1,551 views
0 votes
1 answer
0 votes
1 answer

Can't bind to 'formGroup' since it isn't a known property of 'form'

In order to rectify this error, you ...READ MORE

answered Feb 10, 2022 in Others by Rahul
• 9,680 points
21,287 views
0 votes
1 answer

Now I know what 'pick' does. But I want to do the opposite and remove values from an object.

You can use the keyword Omit for ...READ MORE

answered May 27, 2022 in TypeSript by Nina
• 3,060 points
618 views
0 votes
1 answer

What is TypeScript and why would I use it in place of JavaScript?

TypeScript is a superset of JavaScript which primarily ...READ MORE

answered May 31, 2022 in TypeSript by Nina
• 3,060 points
535 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP