HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Types from both keys and values of object in Typescript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keysfromobjecttypescriptandbothtypesvalues

Problem

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 mapping: one for keys and one for values.

const KeyToVal = {
MyKey1: 'myValue1',
MyKey2: 'myValue2',
};


The keys are easy enough:

type Keys = keyof typeof KeyToVal;


I'm having trouble getting a compile-time type for the values. I thought maybe one of these would work:

type Values = typeof KeyToVal[Keys];
type Values = K extends Keys ? (typeof KeyToVal)[K] : never;
type Prefix = {[V in keyof U]: V}[K];


All of these just made Values to be string. I also tried adapting the two answers to How to infer typed mapValues using lookups in typescript?, but either I got my adaptations wrong, or the answers didn't fit my scenario in the first place.

Solution

Actually, you should change the KeyToVal to the below declaration:
const KeyToVal = {
MyKey1: 'myValue1',
MyKey2: 'myValue2',
} as const; //

Then create the keys types:
type Keys = keyof typeof KeyToVal;


Now you can create the types of the values:
type ValuesTypes = typeof KeyToVal[Keys];
`

Context

Stack Overflow Q#53662208, score: 101

Revisions (0)

No revisions yet.