I have the next object:
const obj1 = {
a: 'x',
b: 'y',
c: 'z',
}
I want obtain type like this, automatically:
type Type = {
x: number,
y: number,
z: number,
}
I have thought something like:
type Type = {[key in Object.values(obj1)]: number}
But obviously this not working.
SOLUTION
With help of @jcalz I managed to do it generic:
type ObjectKeysFromValues<
O extends { [key: string | number]: string | number},
V = string,
> = Record<O[keyof O], V>
And this can be used like this:
const obj2: ObjectKeysFromValues<typeof obj1> = {
x: '1',
y: '1',
z: '1',
}
or
const obj2: ObjectKeysFromValues<typeof obj1, number> = {
x: 1,
y: 1,
z: 1,
}
Maybe I should better the namming 😂
obj1as defined is of type{a: string, b: string, c: string}so there's no way to figure out"x","y", or"z"from that; you need to change your definition ofobj1so that the compiler keeps track of string literal values (hence theas const). Also note that your example has syntax errors; please edit the question to add commas in the appropriate places.