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 😂