Search code examples
typescripttypescript-typings

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?

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