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 in TypeSript by Logan
• 1,580 points
10 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 by Nina
• 2,900 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 in TypeSript by Nina
• 2,900 points
7 views
0 votes
1 answer
0 votes
1 answer

TypeScript Object assign gives me an error property assign does not exist on type ObjectConstructor

For TypeScript 2.1 and higher, you can ...READ MORE

answered May 31 in TypeSript by Nina
• 2,900 points
23 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,310 points
1,798 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,200 points
470 views
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 in Others by Rahul
• 8,980 points
401 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 in TypeSript by Nina
• 2,900 points
12 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 in TypeSript by Nina
• 2,900 points
8 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP