0

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 😂

3
  • Did you try key of (not key in) Commented Apr 24, 2022 at 17:12
  • 2
    Does this approach meet your needs? If so I can write up an answer; if not, what am I missing? Note that your obj1 as 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 of obj1 so that the compiler keeps track of string literal values (hence the as const). Also note that your example has syntax errors; please edit the question to add commas in the appropriate places. Commented Apr 24, 2022 at 17:51
  • That was what i was looking for, If you write the solution I will can check it Commented Apr 25, 2022 at 8:13

1 Answer 1

2

first you should add "as const" after your obj1 definition.

const obj1 = {
  a: "x",
  b: "y",
  c: "z",
} as const;

now you have 2 options to define your type.

1.using index signatures

type Type = {
    [P in typeof obj1[keyof typeof obj1]]: number
}

2.using "Record" that is a built-in utility type like this:

type Type = Record<typeof obj1[keyof typeof obj1], number>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.