Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use the types from the properties of another type

Let’s say I have the following type

type Person = {
  name: string,
  age: number,
  nicknames: string[],
}

And I want to create another type from the types of the properties of the Person type so it ends up like:

 type PersonTypes = string|number|string[]

How can I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried with variations of using keyof and typeof but I can’t achieve it.

>Solution :

You can do that like this:

type PersonTypes = Person[keyof Person]

If you want a reusable generic that can be applied to any type, you can do that like this:

type ValueOf<T> = T[keyof T]
type PersonTypes = ValueOf<Person>

Playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading